node.js - 我应该为错误做些什么对于异步测试和 Hook ,确保调用 "done()";如果返回一个 Promise,确保它 resolve

标签 node.js typescript mocha.js supertest

我正在使用 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();
    });

我该怎么办?

最佳答案

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

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

  1. 在测试或描述 block 中

    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()

关于node.js - 我应该为错误做些什么对于异步测试和 Hook ,确保调用 "done()";如果返回一个 Promise,确保它 resolve,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68079009/

相关文章:

html - 以 HTML 格式语法包含另一个 Jade 文件

node.js - 如何在linux中安装node.tar.xz文件

javascript - req.ip 可以在 Express.js 中伪造吗?

typescript : Object Equality Comparison (Object Equals Object)

javascript - 如何在 Node 中测试事件发射器

node.js - 通过 npm 安装 copay 返回 : cannot run in wd %s %s (wd=%s)

typescript - 如何确定哪个 Jest 测试在超时内无法运行?

javascript - 我需要为 TypeScript 支持的项目使用 Browserify 吗?

javascript - Postman 中是否有一个功能可以在所有其他功能之前只运行一次测试

javascript - 具有未知数组的 chai 子集