使用 Nightwatch 編寫單元測試
概觀
Nightwatch 的單元測試自從 0.9
版本開始提供,並且在 Nightwatch 中編寫的單元測試也完全與 Mocha 的 Exports 介面相容,因此您可以使用任一測試執行器。
單元測試模式
Nightwatch 會自動嘗試連線到 WebDriver 伺服器並建立 Session。在執行單元測試時,需要停用此功能,並讓執行器知道它正在單元測試模式下運作。
這可以透過兩種方式完成
1. 設定 unit_tests_mode=true
這是一個全域選項。在 nightwatch.json
中將 unit_tests_mode
選項設定為 true
{
"src_folders" : ["tests"],
"unit_tests_mode": true
}
2. 為每個測試新增 @unitTest 屬性
如果您希望將個別的測試套件作為單元測試,您可以將 @unitTest
屬性設定為 true。
const assert = require('assert');
module.exports = {
'@unitTest': true,
'demo UnitTest' : function (done) {
assert.equal('TEST', 'TEST');
setTimeout(function() {
done();
}, 10);
}
};
選擇斷言框架
對於單元測試,browser
物件不會作為引數傳遞到測試案例。傳遞的唯一引數是用於非同步測試的 done
回呼。
您可以使用任何您喜歡的斷言框架。Chai.js 是一個相當不錯且非常靈活的框架。
範例
以下是 utils.js
Nightwatch 模組的單元測試子集
const assert = require('assert');
const common = require('../../common.js');
const Utils = common.require('util/utils.js');
module.exports = {
'test Utils' : {
testFormatElapsedTime : function() {
var resultMs = Utils.formatElapsedTime(999);
assert.equal(resultMs, '999ms');
var resultSec = Utils.formatElapsedTime(1999);
assert.equal(resultSec, '1.999s');
var resultMin = Utils.formatElapsedTime(122299, true);
assert.equal(resultMin, '2m 2s / 122299ms');
},
testMakeFnAsync : function() {
function asyncFn(cb) {
cb();
}
function syncFn() {}
var convertedFn = Utils.makeFnAsync(1, syncFn);
var called = false;
convertedFn(function() {
called = true;
});
assert.equal(Utils.makeFnAsync(1, asyncFn), asyncFn);
assert.ok(called);
}
}
};
非同步單元測試
測試函式的引數是可選的 done
回呼,表示測試已完成。如果存在,則必須在非同步作業完成時呼叫回呼。
範例
以下是一個單元測試,檢查如果您未在設定的時間 (10 毫秒) 內叫用 done
回呼,Nightwatch 是否會擲回錯誤。
module.exports = {
const assert = require('assert');
module.exports = {
'demo UnitTest' : function (done) {
assert.equal('TEST', 'TEST');
setTimeout(function() {
done();
}, 10);
}
};
};
使用合併的組態設定
以下範例說明如何在同一個 nightwatch.json
組態檔中合併端對端測試和單元測試。請注意 exclude
和 filter
屬性的用法。
空的 exclude
表示我們想要重設其值,並僅依賴 filter
。
{
"src_folders" : ["./examples/tests", "./examples/unittests"],
"output_folder" : "./examples/reports",
"webdriver" : {
"start_process": true,
"server_path": "node_modules/.bin/chromedriver",
"port": 9515
},
"test_settings" : {
"default" : {
"launch_url" : "https://127.0.0.1",
"desiredCapabilities": {
"browserName": "chrome"
},
"exclude" : "./examples/unittests/*"
},
"unittests" : {
"unit_tests_mode" : true,
"filter" : "./examples/unittests/*",
"exclude" : ""
}
}
}
程式碼涵蓋率
目前,Nightwatch 未提供涵蓋率報表產生器,但這是未來版本規劃中的功能。同時,您可以編寫一個自訂報表產生器,輸出涵蓋率資料。如需詳細資訊,請參閱自訂報表產生器區段,以及 Mocha HTMLCov 報表產生器,了解報表產生器的外觀。
協力廠商涵蓋率服務
有一些託管服務可以在現代 Web 介面中為您提供報表和指標。這些服務通常需要 LCOV 格式的涵蓋率資料。Nightwatch 使用 coveralls.io。
如需 LCOV 報表產生器外觀以及如何與您的專案整合的詳細資訊,您可以查看 mocha-lcov-reporter。