使用程式化 API
概述
當 Nightwatch 作為常規程式庫套件匯入時,會匯出一個 API,以便您可以程式化方式使用 Nightwatch。執行此操作時,可以內嵌提供個別組態設定。因此,無需提供組態檔。但是,從 1.3 版開始,會預設為您的專案建立 nightwatch.conf.js。
語法
Nightwatch 2 帶來全新的程式化 API,讓您可以非常輕鬆地在外部使用 Nightwatch。您可以使用它來建立自訂執行器,或使用 Jest、Mocha 或 Ava 等外部測試執行器。
Nightwatch.createClient([options])
建立可建立 WebDriver 工作階段的新 Nightwatch 用戶端。
語法
custom_test_runner.js
const Nightwatch = require('nightwatch');
const client = Nightwatch.createClient({
headless: true,
output: true,
silent: true, // set to false to enable verbose logging
browserName: 'firefox', // can be either: firefox, chrome, safari, or edge
// set the global timeout to be used with waitFor commands and when retrying assertions/expects
timeout: 10000,
// set the current test environment from the nightwatch config
env: null,
// any additional capabilities needed
desiredCapabilities: {
},
// can define/overwrite test globals here;
// when using a third-party test runner only the global hooks onBrowserNavigate/onBrowserQuit are supported
globals: {},
// when the test runner used supports running tests in parallel;
// set to true if you need the webdriver port to be randomly generated
parallel: false,
// All other Nightwatch config settings can be overwritten here, such as:
disable_colors: false
});
client.updateCapabilities([options])
使用上面列出的 createClient()
方法建立現有的 client
後,可以使用此方法來更新最初指定的功能。
語法
client.updateCapabilities({
testCapability: 'one, two, three'
});
client.launchBrowser()
使用上面列出的 createClient()
方法建立現有的 client
後,可以使用此方法來建立新的瀏覽器工作階段。
傳回的物件將會是 Nightwatch 瀏覽器 API 物件。
語法
const browser = await client.launchBrowser();