【问题标题】:Alternative to using jest.setTimeout替代使用 jest.setTimeout
【发布时间】:2021-01-29 09:30:07
【问题描述】:

目前我在我的 NodeJS/Express/MongoDB 应用程序中配置了一些测试(Jest + Supertest)。 根据我的经验,当服务器实际成功连接到 MongoDB 时(可能需要几秒钟),可能会有很大的不同。

我的测试失败了,因为它在 5000 毫秒后超时(我相信这是 Jests 默认超时)。

我可以通过在测试的第一部分定义一个jest.setTimeout(15000) 来绕过这个问题,它们看起来像这样:

test('POST' + endpointUrl, async () => {
    jest.setTimeout(15000);

    const response = await request(app)
        .post(endpointUrl)
        .send(newTodo);

    ASSERTIONS
});

我想知道这是否是解决我的问题的正确方法。

【问题讨论】:

    标签: node.js unit-testing jestjs integration-testing


    【解决方案1】:

    如果您有异步函数并且必须等待响应,只需使用done 关键字作为测试回调参数即可。

    test('POST' + endpointUrl, async (done) => {
        const response = await request(app)
            .post(endpointUrl)
            .send(newTodo);
    
        ASSERTIONS
        
        done();
    });
    

    或者:

    test('POST' + endpointUrl, done => {
        request(app)
            .post(endpointUrl)
            .send(newTodo)
            .then(res => {
                ASSERTIONS
                done();
            })
            .catch(error => {
                fail(`It must be done, but catched because of: ${error}`);
            })
    });
    

    欲了解更多信息,请查看此主题:Testing Asynchronous Code

    【讨论】:

      猜你喜欢
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-19
      • 2020-01-28
      • 2023-04-10
      相关资源
      最近更新 更多