■ はじめに
https://dk521123.hatenablog.com/entry/2021/02/06/220603
https://dk521123.hatenablog.com/entry/2021/03/07/223957
の続き。 NightWatch で 貯まった知識を少しずつメモする。
目次
【1】実行環境のURLを取得するには 【2】設定ファイルから独自の設定値を取得するには 【3】テスト実行した際、1回 before/beforeEach/afterEach/after を行うには
【1】実行環境のURLを取得するには
実行環境により、ポートが変わったりするので、 ====== browser.url('http://localhost:8080/'); ====== のようにすると、意図しないテストになる。 そうなってしまうので、テスト中に動的にURLをとりたい。
解決案
* browser.launchUrl で取得する
https://nightwatchjs.org/gettingstarted/configuration/#the-launch_url-property
サンプル
// e.g. browser.launchUrl = http://localhost:8080
browser.url(browser.launchUrl);
【2】設定ファイルから独自の設定値を取得するには
https://dk521123.hatenablog.com/entry/2021/03/07/223957
でも行ったが、プロジェクト直下に「nightwatch.json」を用意し 以下のように、test_settings.xxxxx.globals配下を定義する
nightwatch.json
{ "test_settings" : { "default" : { "globals": { "value1": "Hello", "value2": "World!" } } } }
使用例:test.js
module.exports = { 'Demo': (browser) => { console.log(`value1 = ${browser.globals.value1}`); console.log(`value2 = ${browser.globals.value2}`); }, };
出力結果
value1 = Hello value2 = World!
参考文献
https://www.davidmello.com/nightwatch-global-environment-variables/
【3】テスト実行した際、1回 before/beforeEach/afterEach/after を行うには
tests/e2e/globals.js の Global hooks を利用する
サンプル:tests/e2e/globals.js
// ・・・略・・・ /// ////////////////////////////////////////////////////////////// // Global hooks // - simple functions which are executed as part of the test run // - take a callback argument which can be called when an async // async operation is finished /// ////////////////////////////////////////////////////////////// /** * executed before the test run has started, so before a session is created */ before(cb) { console.log('global before'); console.log(`env.NODE_ENV = ${process.env.NODE_ENV}`); cb(); }, /** * executed before every test suite has started */ beforeEach(browser, cb) { console.log('global beforeEach') cb(); }, /** * executed after every test suite has ended */ afterEach(browser, cb) { browser.perform(function() { console.log('global afterEach') cb(); }); }, /** * executed after the test run has finished */ after(cb) { console.log('global after') cb(); }, };
関連記事
Vue + NightWatch で E2Eテスト をする
https://dk521123.hatenablog.com/entry/2021/02/06/220603
NightWatch ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2021/03/04/172003
NightWatch ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2021/03/05/113518
NightWatch ~ カスタムアサーション ~
https://dk521123.hatenablog.com/entry/2021/03/06/234935
NightWatch ~ スナップショットあれこれ ~
https://dk521123.hatenablog.com/entry/2021/03/07/223957
NightWatch に関するトラブルシューティング
https://dk521123.hatenablog.com/entry/2021/02/07/180052