ES6 async/awaitの使用
概要
Nightwatchバージョン 1.1
以降、ES6のasync functionとしてテストを作成できます。
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]);
}
};