首页 > 解决方案 > 如何让噩梦强行超时

问题描述

正如标题所暗示的那样,我正在尝试强制使我的脚本超时,特别是如果不满足条件(返回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);
        })
  });
});

如果我的代码中有任何其他错误,请随时告诉我。

标签: javascriptnode.jstypescriptmocha.jsnightmare

解决方案


您可以使用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()处理程序触发,那是因为噩梦请求失败或您遇到了超时。您可以通过查看您收到的拒绝错误对象来判断它是哪一个。

请注意,噩梦中还内置了各种超时选项,如此处的文档中所述。无论超时的确切目的是什么,您都可能会发现其中一个内置选项适合。


推荐阅读