如何在then()内结束异步mocha测试

时间:2017-04-09 04:48:36

标签: mocha chai

我需要在我的测试中执行两个连续的POST,所以我将第二个嵌套在then()内的回调中。当我尝试运行测试时,出现此错误:Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

这是我的代码:

it('it should not create a user with a username already in the database', (done) => {
        let user = {
            "username": "myusername",
            "password": "password"
        };
        chai.request(server)
            .post('/user')
            .send(user)
            .then((response) => {
                chai.request(server)
                .post('/user')
                .send(user)
                .then((res) => {
                    res.should.have.status(406);
                    done();
                }); 
            });
 });

我已尝试增加超时限制,但这不起作用。我在这里缺少什么?

3 个答案:

答案 0 :(得分:0)

您应始终拥有.catch

.then(response => ...)
.catch(e => assert.equal(e.message, "Expecting data"))

答案 1 :(得分:0)

Mocha supports promises,如果您正在测试基于承诺的代码,最好使用该支持:

it('it should not create a user with a username already in the database', () => {
  let user = {
    "username": "myusername",
    "password": "password"
  };
  return chai.request(server)
    .post('/user')
    .send(user)
    .then((response) => {
      return chai.request(server)
        .post('/user')
        .send(user)
        .then(() => {
          // We're _expecting_ a promise rejection, so throw if it resolves:
          throw Error('should not be reached');
        }, res => {
          res.should.have.status(406);
        }); 
    });
});

否则,可能会发生以下情况:断言(res.should.have.status(406))可能会失败,从而引发错误,导致done永远不会被调用,从而导致超时。

您可以使用.catch捕获该断言错误并使用错误调用done,但您必须为所有测试执行此操作,这有点单调乏味。它也容易出错,因为如果由于某种原因,在.catch内抛出新错误,你最终会遇到同样的问题。

答案 2 :(得分:0)

好的,我明白了。在这篇文章中找到答案:When testing async functions with Mocha/Chai, a failure to match an expectation always results in a timeout

它永远不会打到done次来电的原因是它遇到了一个未被捕获的异常并且从未返回过。我没有在then内部提供故障回调,并且抛出了Not Acceptable异常。

这是我的固定代码:

it('it should not create a user with a username already in the database', (done) => {
        let user = {
            "username": "anh",
            "password": "pass"
        };
        chai.request(server)
            .post('/user')
            .send(user)
            .then((response) => {
                chai.request(server)
                .post('/user')
                .send(user)
                .then(() => {
                    throw Error('Something went wrong');
                },
                (res) => {
                    res.should.have.status(406);
                    done();
                });
            },
            (res) => {
                throw Error('Something went wrong');
            });
    });