將 CucumberJS 與 Nightwatch 搭配使用
概觀
Nightwatch 2 帶來直接將 Cucumber.js 作為替代測試執行器的整合支援。除了 Cucumber 程式庫 本身(7.3 或更高版本)外,不需要其他外掛程式。
只需在也安裝了 Nightwatch 的同一個專案中執行下列程式碼即可
npm i @cucumber/cucumber --save-dev
組態設定
為了在 Nightwatch 中使用 CucumberJS,您需要設定 test_runner
組態屬性,並將類型設定為 cucumber
。您還需要設定 feature 檔案所在位置的路徑。
{
test_runner: {
// set cucumber as the runner
type: 'cucumber',
// define cucumber specific options
options: {
//set the feature path
feature_path: 'examples/cucumber-js/*/*.feature',
// start the webdriver session automatically (enabled by default)
auto_start_session: true,
// use parallel execution in Cucumber
// set number of workers to use (can also be defined in the cli as --parallel 2
parallel: 2
}
},
src_folders: ['examples/cucumber-js/features/step_definitions']
}
執行測試
從範例執行 Cucumber 測試的最簡單方式是
npx nightwatch --env cucumber-js
Cucumber 規格檔案/步驟定義檔案可在 Nightwatch 組態中的 src_folders
中提供,或作為 CLI 引數提供。
使用定義的 src_folders
npx nightwatch
不使用定義的 src_folders
npx nightwatch examples/cucumber-js/features/step_definition
平行執行
使用 2 個工作人員平行執行
nightwatch examples/cucumber-js/features/step_definitions --parallel 2
像往常一樣使用其他測試執行器選項
npx nightwatch examples/cucumber-js/features/step_definitions --headless
手動啟動 WebDriver 工作階段
有時您可能需要在 Nightwatch 執行個體化之後,不要自動啟動 Webdriver 工作階段。為此,Nightwatch 提供以 this.client
形式提供的執行個體,其中包含 launchBrowser()
方法。
組態設定
{
test_runner: {
type: 'cucumber',
options: {
feature_path: 'examples/cucumber-js/*/*.feature',
auto_start_session: false
}
}
}
然後,您可以使用可以作為額外 --require
傳遞給 Nightwatch 的額外設定檔,該檔案將會轉送到 Cucumber。在額外設定檔中,您可以加入在工作階段啟動之前需要執行的其他作業。
範例 _extra_setup.js
請記得在 this
上設定 browser
,以便 Nightwatch 可以自動關閉它。否則,請記得在您自己的 Cucumber After()
Hook 中呼叫 .quit()
。
const {Before} = require('@cucumber/cucumber');
Before(async function(testCase) {
if (!this.client) {
console.error('Nightwatch instance was not created.');
return;
}
this.client.updateCapabilities({
testCap: 'testing'
});
this.browser = await this.client.launchBrowser();
});
使用額外設定執行
nightwatch examples/cucumber-js/features/step_definitions --require {/full/path/to/_extra_setup.js}
Cucumber 的 Nightwatch 設定檔
您可能也會想要檢查 Nightwatch 用於初始化 Cucumber 執行器的內建設定檔。它可以在我們的專案根資料夾的 /cucumber-js/_setup_cucumber_runner.js 中找到。
報告
當使用整合的 Cucumber 測試執行器時,您需要使用 Cucumber 格式器 來產生輸出。
如果存在,Nightwatch 將會把 --format
和 --format-options
CLI 引數轉送到 Cucumber。
預設會使用 progress
格式器。
例如
npx nightwatch --env cucumber-js --format @cucumber/pretty-formatter
或
npx nightwatch --env cucumber-js --require cucumber.conf.js --format json:report/cucumber_report.json
範例輸出
以下是在 Firefox 中執行範例測試時的輸出外觀。您可以在安裝了 Nightwatch 的專案中執行此操作
npx nightwatch examples/cucumber-js/features/step_definition