【问题标题】:Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout超时 - 在 jest.setTimeout 指定的 5000 毫秒超时内未调用异步回调
【发布时间】:2019-03-11 20:17:27
【问题描述】:

我正在使用 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: 'test@test.com',
        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: 'test@test1.com',
        password: 'welcome1',
      })
      .expect(200);
    done();
    //expect(response.statusCode).toBe(200);
  });
});

如果我有单个测试,它工作正常,但里面有多个测试描述,它显示超时错误。

以下是错误截图:

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

请大家帮忙!

【问题讨论】:

  • 你解决过这个问题吗?

标签: reactjs express jestjs supertest


【解决方案1】:

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

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

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

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

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

选项2:使用end方法

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

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

【讨论】:

    【解决方案2】:

    一个可能的问题可能与 express 中间件有关。 要确定您是否属于这种情况,您可以:

    1. 注释掉你的 express 应用的所有中间件 (app.use(/* middleware */)docs)
    2. 查看测试是否开始以某种方式进行(通过/不超时)
    3. 开始取消对中间件的注释,将其缩小到罪魁祸首。

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

    1. 通过在目录中创建__mocks__ 来模拟第三方库 你的根目录并插入一个文件library_name.js(这是 手动嘲讽: documentation)
    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 显示另一个错误提示商店连接问题。

    【讨论】:

      猜你喜欢
      • 2018-09-18
      • 2018-09-11
      • 2019-04-23
      • 2020-05-13
      • 2018-12-28
      • 2021-05-13
      • 2018-12-05
      • 2020-12-09
      相关资源
      最近更新 更多