【NightWatch】NightWatch ~ カスタムコマンド ~

■ はじめに

https://dk521123.hatenablog.com/entry/2021/02/06/220603 https://dk521123.hatenablog.com/entry/2021/03/07/223957 https://dk521123.hatenablog.com/entry/2021/03/06/234935

の続き。

NightWatch で よく使う処理(例えば、ログインなど)を
カスタムコマンドの形にして呼び出すことができるので、メモする。

目次

【1】カスタムコマンドを作ってみる
 例1:Hello world
 例2:Homeに移動する
【2】カスタムコマンドの保存先を変更するには

【1】カスタムコマンドを作ってみる

例1:Hello world

tests/e2e/custom-commands/sayHello.js

/**
 * A very basic Nightwatch custom command. The command name is the filename and the
 *  exported "command" function is the command.
 *
 * Example usage:
 *   browser.sayHello('Mike');
 *
 * For more information on writing custom commands see:
 *   https://nightwatchjs.org/guide/extending-nightwatch/#writing-custom-commands
 *
 * @param {string} name
 */
exports.command = function (name) {
  console.log(`Hi, ${name}`);
};

tests/e2e/specs/test.js

module.exports = {
  before(browser) {
    browser.sayHello('Mike');
  },
・・・略・・・
};

出力結果

Hi, Mike

例2:Homeに移動する

tests/e2e/custom-commands/moveToHome.js

exports.command = function () {
  console.log('Start command');
  this.init();
  this.url(this.launchUrl);
  this.waitForElementVisible('body');
  console.log('End command');
};

tests/e2e/specs/test.js

module.exports = {
  before(browser) {
    browser.moveToHome();
  },
・・・略・・・
};

【2】カスタムコマンドの保存先を変更するには

* プロジェクトフォルダ直下に設定ファイル nightwatch.json を作成し、
 custom_commands_path に指定する。

nightwatch.json

 {
    "custom_commands_path" : "./examples/custom-commands",
・・・略・・・

参考文献
https://qiita.com/KWS_0901/items/440b1f8dd8b5ea92ba9f
https://github.com/nightwatchjs/nightwatch/blob/master/bin/nightwatch.json
https://github.com/maxgalbu/nightwatch-custom-commands-assertions/blob/master/Readme.md

参考文献

https://qiita.com/frost_star/items/cd3956d20fee085f9ef8

関連記事

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/03/08/235438
NightWatch に関するトラブルシューティング
https://dk521123.hatenablog.com/entry/2021/02/07/180052