【问题标题】:Mocha Chai Tests Pass buth shouldn'tMocha Chai 测试通过但不应该
【发布时间】:2018-01-31 22:42:55
【问题描述】:

这是当前的测试:

  describe('/POST Register Page', function() {
    it('it should register new user', function(/*done*/) {
      chai.request(server)
        .post('/auth/register')
        .send(new_user_data)
        .end(function(res) {
          expect(res).to.have.status(2017);
          // done();
        })
    })
  })

我上次检查,没有2017的http代码,但是,它仍然通过:

Registration
    Get register page
GET /auth/register 200 6.989 ms - 27
      ✓ it should get register page
    /POST Register Page
      ✓ it should register new user


  2 passing (147ms)

我想简单地发布一些东西,然后得到回复,然后玩弄回复。

如果我包含done(),我会收到超时错误:

1) Registration /POST Register Page it should register new user:
     Error: Timeout of 3000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

我什么都做不了,至于对错,测试通过了。

虽然这个 get 请求按预期传递:

  describe('Get register page', function() {
    it('it should get register page', function(done) {
      chai.request(server)
        .get('/auth/register')
        .end(function(err, res) {
          expect(err).to.be.null;
          expect(res).to.have.status(200);
          done();
        })
    })
  })

我是 mocha-cum-chai-chai-http 的新手,到目前为止的体验很奇怪。

谢谢。

【问题讨论】:

  • 如果你打算不使用done 回调(如果你有你不应该使用的Promises),那么只需返回chai.request。只需确保您启用了Promise feature

标签: mocha.js chai


【解决方案1】:

您的 POST 请求可能需要超过 3 秒才能完成,因此 mocha 会引发超时错误。

您可以尝试将超时设置为更大的值,例如:

describe('/POST Register Page', function() {
  // timeout in milliseconds
  this.timeout(15000); 

  // test case
  it('it should register new user', function(done) {
    chai.request(server)
      .post('/auth/register')
      .send(new_user_data)
      .end(function(res) {
        expect(res).to.have.status(200);
        done();
      })
  })
})

通过一些试验,您可以找出在测试中设置的最佳超时值。

当您不使用done() 回调时,mocha 只是跳过断言而不等待实际响应到达。由于.end() 块中的断言永远不会被执行,所以 mocha 通过了测试,因为它没有遇到任何断言。当我第一次开始使用 TDD 时,我也遇到过类似的情况,我是通过艰难的方式了解到这一点的。

Reference

因为结束函数被传递了一个回调,所以断言被运行 异步。因此,必须使用一种机制来通知 回调已完成的测试框架。否则,测试 将在检查断言之前通过。

【讨论】:

    猜你喜欢
    • 2017-07-18
    • 2018-04-17
    • 2014-08-06
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多