javascript - 如何让噩梦强行超时
问题描述
正如标题所暗示的那样,我正在尝试强制使我的脚本超时,特别是如果不满足条件(返回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 处理结束。如果Promise.race(...).then()
处理程序触发,那是因为您的噩梦请求在超时之前完成。如果Promise.race(...).catch()
处理程序触发,那是因为噩梦请求失败或您遇到了超时。您可以通过查看您收到的拒绝错误对象来判断它是哪一个。
请注意,噩梦中还内置了各种超时选项,如此处的文档中所述。无论超时的确切目的是什么,您都可能会发现其中一个内置选项适合。
推荐阅读
- powershell - 如何在 Windows 终端 powershell 选项卡中运行 powershell 脚本(.ps1)?
- html - DevTools 无法加载 SourceMap:无法加载 http://localhost:3000/javascripts/bootstrap.js.map 的内容:HTTP 错误:状态代码 404,网络:
- android - Android NFC 可以在没有用户输入/操作或没有通知的情况下工作吗?
- networking - 使用 ESXi 将独立的物理系统与构建在系统内部的 VM 联系起来
- javascript - 带有 ReactJs 的 Firebase - 行的顺序有问题
- visual-studio-code - VSCode复制粘贴单词列表,同时保持一般结构
- python - 如何将我的 Flask_socketio 应用正确推送到 Heroku?
- docker - 如何将 apache-superset 与 apache-drill 连接起来?
- c++ - 读取无效数据 c6385
- swiftui - 如何从列表元素更新全局状态?