使用 'exports' 測試語法
總覽
Nightwatch 用於編寫測試的預設介面是 exports
語法,這使得編寫端對端測試非常容易。
雖然這種格式稍微容易理解和使用,但它也比 BDD describe()
介面更受限制。由於 describe()
作為測試格式的廣泛使用以及與 Mocha 等工具的相容性,我們建議使用 BDD describe()
,但 exports
也將繼續正常運作。
範例
以下基本測試套件範例開啟搜尋引擎 Ecosia.org,搜尋術語 nightwatch
,然後驗證第一個結果是否為 Nightwatch.js
網站。
tests/sampleTest.js
module.exports = {
'Demo test ecosia.org' : function(browser) {
browser
.url('https://www.ecosia.org/')
.waitForElementVisible('body')
.assert.titleContains('Ecosia')
.assert.visible('input[type=search]')
.setValue('input[type=search]', 'nightwatch')
.assert.visible('button[type=submit]')
.click('button[type=submit]')
.assert.containsText('.mainline-results', 'Nightwatch.js')
.end();
}
};
您也可以在測試中包含多個步驟,如下所示
tests/sampleTest.js
module.exports = {
'step one: navigate to ecosia.org': function(browser) {
browser
.url('https://www.ecosia.org')
.waitForElementVisible('body')
.assert.titleContains('Ecosia')
.assert.visible('input[type=search]')
.setValue('input[type=search]', 'nightwatch')
.assert.visible('button[type=submit]');
},
'step two: click submit' : function (browser) {
browser
.click('button[type=submit]')
.assert.containsText('.mainline-results', 'Nightwatch.js')
.end();
}
};
使用 ES 模組 (ESM)
如果您的專案中使用 ES 模組,您需要使用以下格式編寫測試
tests/sampleTest.js
exports default {
'Demo test ecosia.org' : function(browser) {
browser
.url('https://www.ecosia.org/')
.waitForElementVisible('body')
.assert.titleContains('Ecosia')
.assert.visible('input[type=search]')
.setValue('input[type=search]', 'nightwatch')
.assert.visible('button[type=submit]')
.click('button[type=submit]')
.assert.containsText('.mainline-results', 'Nightwatch.js')
.end();
}
};
您還需要使用 nightwatch.conf.cjs
組態檔。
我們整理了一個完整的 Github ESM 範本儲存庫,其中包含幾個範例,我們正在定期更新,包括一個 Github Actions 工作流程,供您開始使用。
測試標籤
您還可以根據標籤選擇性地指定要執行的測試,以便測試可能屬於多個標籤。例如,您可能有一個登入測試,它屬於 login
套件和 sanity
套件。
標籤可以使用將 @tags
屬性新增至測試模組來完成
tests/sampleTest.js
module.exports = {
'@tags': ['login', 'sanity'],
'demo login test': function (browser) {
// test code
}
};
若要選取要執行的標籤,請使用 --tag
命令列旗標
nightwatch --tag login
將多個標籤指定為
nightwatch --tag login --tag something_else
若要跳過執行具有特定標籤的測試,請使用 `--skiptags` 旗標
nightwatch --skiptags login
或者若要跳過多個標籤,請將您要跳過的每個標籤新增為逗號分隔
nightwatch --skiptags login,something_else