概述

從 Nightwatch 版本 1.1 開始,您可以將測試撰寫為 ES6 async 函數

async 函數使 API 指令能夠返回 promise,並使其可以使用 await 運算子來擷取結果,而不是像預設情況下那樣的回呼。

使用 async 函數可大大提高測試的可讀性和撰寫的容易性。從 Nightwatch 版本 1.7 開始,也支援在使用 async 函數時鏈接 API 指令。

範例

tests/exampleTest.js
module.exports = {
  'demo test async': async function (browser) {
    // get the available window handles
    const result = await browser.windowHandles();
    console.log('result', result);
    
// switch to the second window // await is not necessary here since we're not interested in the result browser.switchWindow(result.value[1]); } };

搭配 async 使用回呼

回呼仍然可以像以前一樣使用,如果回呼返回 Promise,則 promise 的結果就是指令的結果,如下列範例程式碼所示

tests/exampleTest.js
module.exports = {
  'demo test async': async function (browser) {
    // get the available window handles
    const value = await browser.windowHandles(function(result) {
      // we only want the value, not the entire result object
      return Promise.resolve(result.value);
    });
    
console.log('value', value);
// switch to the second window browser.switchWindow(value[1]); } };