超时 - 在 jest.setTimeout 指定的 5000 毫秒超时内未调用异步回调

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

我正在使用 jest 测试用户功能(注册和登录)的 API。

测试代码:

const request = require('supertest');
const app = require('../../app');

describe('Test User Functionality', () => {  
  test('User should be able to login', async done => {
    const response = await request(app)
      .post('/api/users/login')
      .send({
        email: '[email protected]',
        password: 'welcome1',
      })
      .expect(200);
    done();
    //expect(response.statusCode).toBe(200);
  });
  test('User should be able to signup', async done => {
    const response = await request(app)
      .post('/api/users/signup')
      .send({
        username: 'testuser',
        email: '[email protected]',
        password: 'welcome1',
      })
      .expect(200);
    done();
    //expect(response.statusCode).toBe(200);
  });
});

如果我有单个测试,它工作正常,但在描述内进行多个测试,它会显示超时错误。

以下是错误截图:

我尝试添加超时,交换测试,但仍然没有成功。

请大家帮忙!

reactjs express jestjs supertest
2个回答
0
投票

我在使用异步请求测试我的反应组件时遇到了同样的问题。

发生这种情况是因为您没有正确完成您的请求。

您可以轻松解决这个问题。

选项 1:将

done
移动为
expect
函数调用的第二个参数,如下所示。

const response = await request(app)
  .post('/api/users/signup')
  .send({
    username: 'testuser',
    email: '[email protected]',
    password: 'welcome1',
  })
  .expect(200, done);

选项2:使用

end
方法

const response = await request(app)
      .post('/api/users/signup')
      .send({
        username: 'testuser',
        email: '[email protected]',
        password: 'welcome1',
      })
      .expect(200)
      .end((err, res) => { 
        // do anything you want! 
      })

或者你可以查看文档(https://github.com/visionmedia/supertest#readme)!


0
投票

一个可能的问题可能与快速中间件有关。 要了解您是否属于这种情况,您可以:

  1. 注释掉您的 Express 应用程序的所有中间件 (
    app.use(/* middleware */)
    docs)
  2. 查看测试是否开始以某种方式取得进展(通过/未超时)
  3. 开始取消中间件的注释,以缩小罪魁祸首的范围。

一旦找到超时的原因,您就可以进行更深入的研究。 模拟导致问题的中间件的不同部分:

  1. 通过创建目录
    __mocks__
    来模拟第三方库 你的根目录并插入一个文件
    library_name.js
    (这是 手动嘲笑笑话: 文档
  2. 模拟中间件并通过它们直接调用 next
    app.use(Your.Middleware)
    并在中间件文件中
/** Possibly imports and some setup here */

// Make sure the function being called is mocked
export default {
    Middleware: (req, res, next) => {
        next();
    },
}

(包含中间件的文件可能包含一些可能导致问题的额外设置。)

我的具体情况: 我在中间件和 Redis 实例化的文件中使用

ioredis
,它多次尝试连接到存储,这导致了超时。
事实证明主机名是错误的。暴露问题的关键是模拟中间件并找到额外的设置。然后 Jest 显示了另一个错误,暗示商店连接问题。

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