[英]How to make nightmare forcefully timeout
顧名思義,我試圖強制使腳本超時,特別是在不滿足條件(返回done()
)的情況下。
這是一些代碼:
import * as Nightmare from "nightmare";
describe("Login Page", function() {
this.timeout("30s");
let nightmare = null;
beforeEach(() => {
nightmare = new Nightmare({ show: true });
});
let pageUrl;
describe("give correct details", () => {
it("should log-in, check for current page url", done => {
nightmare
.goto(www.example.com/log-in)
.wait(5000)
.type(".input[type='email']", "username")
.type(".input[type='password']", "password")
.click(".submit")
.wait(3000)
.url()
.exists(".navbar")
.then(function(result) {
if (result) {
done();
} else {
console.log("failure");
// I want it to timeout here
}
})
.catch(done);
})
.end()
.then(url => {
pageUrl = url;
console.log(pageUrl);
})
});
});
如果我的代碼中有其他錯誤,請隨時告訴我。
您可以使用Promise.race()
來實現超時。 我不知道您的測試代碼,因此我只展示讓您在噩夢請求上超時的內部部分,您可以將其插入測試框架。
// utility function that returns a rejected promise after a timeout time
function timeout(t, msg) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error(msg));
}, t);
});
}
Promise.race([
nightmare
.goto(www.example.com / log - in )
.wait(5000)
.type(".input[type='email']", "username")
.type(".input[type='password']", "password")
.click(".submit")
.wait(3000)
.url()
.exists(".navbar")
.end()
, timeout(5000, "nightmare timeout")
]).then(result => {
// process successful result here
}).catch(err => {
// process error here (could be either nightmare error or timeout error)
});
這里的概念是,您在噩夢請求中的承諾與超時中的承諾之間進行競賽。 解決或拒絕先贏者中的任何一個,並導致諾言處理的結束。 如果Promise.race(...).then()
處理函數觸發,那是因為您的噩夢請求已在超時之前完成。 如果Promise.race(...).catch()
處理程序觸發,那是因為噩夢請求失敗或您超時。 您可以通過查看拒絕對象得到的錯誤對象來判斷是哪一個。
請注意,噩夢中還內置了各種超時選項,如此處的文檔所述。 無論超時的確切目的是什么,您都可能會發現其中一種內置選項適用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.