Nightwatch101 #24:客製化指令(Custom Commands)

Nightwatch.js

Nightwatch 允許開發者定義自己的客製化指令(Custom Commands),這對將常用的功能抽出來成為模組,很有幫助。

♡(´∀`)人(´∀`)♡

本系列文章皆使用這個專案,可以拉下來玩玩;有什麼問題都可以提出 issue


如何使用客製化指令?來 Step-by-Step 一步步完成。

Step 1:新增資料夾存放客製化指令

每一個客製化指令存放在單獨的檔案,檔名即指令名稱,並放在指定資料夾內。範例檔案結構如下所示,這個有一個專門放客製化指令的資料夾 custom_commands

nightwatch101
  ├── custom_assertions
  ├── custom_commands (放置客製化指令)
  ├── page_objects
  ├── reports
  ├── screenshots
  ├── test/e2e
  ├── globals.js
  ├── nightwatch.conf.js
  ├── package.json
  └── README.md

Step 2:設定檔案路徑

Nightwatch Test Runner 必須要知道客製化指令的所在位置,因此必須在 nightwatch.conf.jscustom_commands_path 設定檔案路徑。

const config = {
  "src_folders": [
    "test/e2e"
  ],
  "custom_commands_path": './custom_commands',
  "selenium": {
    // 省略
  }
}

參考完整範例

Step 3:開始撰寫製化指令

這是一個計算指定網頁元素數目的指令,可參考這支檔案-countElementNumber.js

這裡會傳入兩個參數,第一個是 CSS Selector,準備要在頁面上選取的元素;第二個是 callback,數完元素個數後可以做一些事情。return this 用於後續能繼續使用鍊結呼叫的方式使用 browser 底下的其他 API。

exports.command  = function (selector, callback) {
  callback = callback || function() {};

  this.execute(function(selector) {
    return document.querySelectorAll(selector).length;
  }, [selector], function(result) {
    callback.call(this, result);
  });

  return this;
};

Step 4:使用客製化指令

範例如下,打開特定網頁,計算符合 selector <a> 的元素個數,最後結束 session。

module.exports = {
  'Demo Ruten MainCategory Page': browser => {
    browser
      .url('http://class.ruten.com.tw/category/main?0008')
      .countElementNumber('a', function(result) {
        console.log(result.value);
      })
      .end()
  }
}

啟動單檔測試。

nightwatch ./test/e2e/class/testMainCategoryCustomCommands.js

執行結果。

客製化指令(Custom  Commands)

在優化測試程式碼上,將常用的功能抽出來成為模組,成為客製化指令,減少維護的複雜度,應多多使用。注意指令命名的語意化,要清楚明瞭、具備可讀性。

參考資料


下一篇來看客製化斷言(Custom Assertions)。


2018 鐵人賽網址


Nightwatch End-to-End Testing 端對端測試 自動化測試 Nightwatch101 Selenium 鐵人賽 2018鐵人賽 Nightwatch101 2018 iT 邦幫忙鐵人賽 系列文