为什么 JEST 在使用不同的语法时会在异步回调上引发超时?

问题描述 投票:0回答:1

我正在 Node.js 中使用 Jest 进行学习。

当我的测试失败并在 5000 毫秒后超时时,在找到第一个修复程序后,我遇到了一些麻烦。

奇怪的是,我的代码使用以下语法:

// This works
test('It should respond with 200 success', async () => {
    const response = await request(App).get('/launches'); 
    expect(response.statusCode).toBe(200);
});

但是,它不适用于测试用例中通常使用的替代语法:

// This does not work
test('It should respond with 200 success', async () => {
    const response = await request(App)
        .get('/launches')
        .expect('Content-Type', /json/) 
        .expect(200);
});

到目前为止我尝试过的事情

我尝试按如下方式配置我的测试:

// jest config file
module.exports = {
  testEnvironment: "node",
};

// Mongoose DB connection config modification in server.js file
mongoose.set("strictQuery", false);

上面提到的配置修复适用于第一个测试用例,但第二个测试用例仍然失败。这是我的第二个测试用例的测试套件抛出的错误:

    : Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout
- Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

describe('Test GET/ launches', () => {
    test('It should respond with 200 success', async () => {
    ^
        const response = await request(App)
            .get('/launches')
            .expect('Content-Type', /json/)

版本规格:

节点:12.19.0

开玩笑:26.6.3

超级测试:6.1.3

猫鼬:6.3.8

node.js jestjs
1个回答
0
投票

显然,经过一番尝试和错误,我找到了解决方案,只需增加测试函数的超时时间即可。就我而言,将其设置为 6000ms 可以解决问题。可能的原因是与 MongoDB Atlas 的连接速度较慢。超时总是会改变。写在这里,希望能帮助到其他遇到类似问题的人。

test('It should respond with 200 success', async () => {
    const response = await request(App)
        .get('/launches')
        .expect('Content-Type', /json/) 
        .expect(200);
}, 6000); 

但是,更好的方法是有一个单独的数据库连接脚本,可以在多个地方连接和断开连接。这也可以解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.