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

时间:2018-10-06 15:28:16

标签: reactjs express jestjs supertest

我正在使用笑话来测试用户功能(注册和登录)的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);
  });
});

如果我有一个测试,它可以正常工作,但是内部描述了多个测试,则显示超时错误。

下面是错误的屏幕截图:

enter image description here

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

任何人都请帮忙!

2 个答案:

答案 0 :(得分:0)

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

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

您可以轻松解决此问题。

选项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)!

答案 1 :(得分:0)

一个可能的问题可能是表达中间件。 要找出是否属于您的情况,您可以:

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

一旦发现超时的原因,就可以更进一步。 模拟导致问题的中间件的不同部分:

  1. 通过在以下目录中创建目录__mocks__模拟第三方库 您的根目录并插入文件library_name.js(这是 开玩笑的手动嘲笑: documentation
  2. 模拟中间件并通过使其直接调用下一个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显示了另一个提示商店连接问题的错误。

相关问题