【问题标题】:what should i do for error For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves我应该怎么做对于异步测试和钩子,确保调用“done()”;如果返回一个 Promise,确保它解决
【发布时间】:2021-09-05 18:42:34
【问题描述】:

我正在使用 mocha 进行测试

it('should allow a POST to /users', async function () {
        
        const res = await request.post('/users').send(firstUserBody);
    
        expect(res.status).to.equal(201);
        expect(res.body).not.to.be.empty;
        expect(res.body).to.be.an('object');
        expect(res.body.id).to.be.a('string');
        firstUserIdTest = res.body.id;
        
    });

但我有一个错误

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

如果我使用 done() 执行此操作,则该函数不是异步的,但它应该是

it('should allow a POST to /users', async function (done) {

        const res = await request.post('/users').send(firstUserBody);

        expect(res.status).to.equal(201);
        expect(res.body).not.to.be.empty;
        expect(res.body).to.be.an('object');
        expect(res.body.id).to.be.a('string');
        firstUserIdTest = res.body.id;
        done();
    });

我该怎么办?

【问题讨论】:

  • 不异步是什么意思?
  • 我修复了代码 2,如果我编写像 2 这样的代码,'await' 会出错。
  • 什么样的错误?
  • 并且是否 POST 会在 2 秒内解决?如果测试回调是异步的,则不需要接受 done 参数。
  • idk 但似乎没有。我有超过 2000 毫秒的超时错误

标签: node.js typescript mocha.js supertest


【解决方案1】:

在 Mocha 中有两种设置超时的方法:

(测试 API 调用时我会使用至少 20 秒)

  1. 在测试或描述块内

    describe('a suite of tests', function() {
      this.timeout(20000);
      ...
    

    (注意不要使用箭头函数,因为这会导致this. 不起作用)

    见:https://mochajs.org/#timeouts

  2. 配置级别 - .mocharc.js 运行时的文件或标志--timeout 20000 甚至使用 API 设置选项 (mocha.setup())。

    我更喜欢使用.mocharc.js.,您可以在其中放置以下内容:

    module.exports = {
      bail: true,
      timeout: 5 * 60 * 1000, // 5 minute timeout
      spec: ['specs/']
    };
    

文档和示例:

https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js

https://mochajs.org/#configuring-mocha-nodejs

https://mochajs.org/#-timeout-ms-t-ms

PS 你不应该需要带有异步功能的done()

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 2017-10-24
    • 2020-11-19
    • 2019-07-30
    • 2018-06-07
    • 2019-06-14
    • 1970-01-01
    • 2020-05-12
    • 2021-09-13
    相关资源
    最近更新 更多