首页 > 解决方案 > jest.setTimeout.Error:使用 Jest 和 Supertest 模拟 Express 中间件

问题描述

我想模拟 auth 中间件函数总是只调用next(). 为了尝试实现这一点,我在测试文件的开头添加了以下内容,然后将 auth 中间件功能添加到app.js.

jest.mock('../../middleware/auth.js', () =>
  // ensure func is mocked before being attached to the app instance
  jest.fn((req, res, next) => next()) // seems to only work for first request that hits this middleware
); // Mock authentication

然后我在 auth 中间件中添加了一些调试,但在任何测试中都没有命中它们。

目前我正在使用以下内容,当beforeEach()函数没有被注释掉时,测试全部通过:

角色.test.js

jest.mock('../../middleware/auth.js', () =>
  // ensure func is mocked before being attached to the app instance
  jest.fn((req, res, next) => next()) // seems to only work for first request that hits this middleware
); // Mock authentication

const request = require('supertest');
const app = require('../../app.js');
const Role = require('../../../db/models/index.js').Role;
// const auth = require('../../middleware/auth.js');
/**
 * Test role API routes
 */
describe('role-router', () => {
  let res;
  const token = 'valid-token';
  const baseUrl = '/private/api/roles';

  // Without the `beforeEach()` only the first request sent using supertest will use the mocked functionality
  // With the `beforeEach()` everything functions as expected, but why?
  // beforeEach(() => {
  //   auth.mockImplementation((req, res, next) => next());
  // });

  describe(`Create new role | post ${baseUrl}`, () => {
    describe('When successful', () => {
      beforeAll(async () => {
        // this will use the proper mocked functionality
        res = await request(app)
          .post(baseUrl)
          .set('Authorization', token)
          .send({
            roleName: 'Secret Agent',
            roleDesc: "World's best secret agent",
            ...
          });
      });

      // passes
      it('Should return 201', () => {
        expect(res.status).toBe(201);
      });
    }); // When successful
  }); // Create new role

  describe(`Delete role by id | delete ${baseUrl}/:id`, () => {
    describe('When successful', () => {
      beforeAll(async () => {
        const role = await Role.create({
          roleName: 'Secret Agent',
          roleDesc: "World's best secret agent",
          ...
        });
        
        // fails does not get response, res remains the same as res from previous test
        res = await request(app)
          .delete(`${baseUrl}/${role.id}`)
          .set('Authorization', token)
          .send();
      });

      // fails with 201
      it('Should return 204', () => {
        expect(res.status).toBe(204);
      });
    }); // When successful
  }); // Delete role
}); 

收到错误:

 ● role-router › Delete role by id | delete /private/api/roles/:id › When successful › Should return 204

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

      at mapper (node_modules/jest-jasmine2/build/queueRunner.js:29:45)

应用程序.js

// Dependencies
const express = require('express');
const auth = require('./middleware/auth.js');
...

/**
 * Express application
 */
const app = express();

// Middleware
app.use(express.json());
...

// Private routes are secured with jwt authentication middleware
app.all('/private/*', (req, res, next) => auth(req, res, next));

// Public routes
...

// Private routes
app.use('/private/api/roles/', require('./components/role/role-router.js'));
...

module.exports = app;

任何想法为什么在每次测试之前不使用该beforeEach()函数来模拟中间件功能时这不起作用?也许我错过了更严重的事情?

标签: node.jsexpressjestjssupertest

解决方案


这种行为的原因是存在spy.mockReset(),jest.resetAllMocks()或启用的resetMocks配置选项。使用restoreMocksoption 代替合理的默认配置。

jest.fn(() => ...)和之间的区别在于jest.fn().mockImplementation(() => ...)他们如何回应jest.restoreAllMocks()restoreAllMocks恢复原始实现,在 的情况下是无操作的jest.fn(),而在 的情况下() => ...被认为是原始实现jest.fn(...)。因此,通常jest.fn(() => ...)不会重置实现。

jest.resetAllMocks和之间的区别在于jest.restoreAllMocks前者可以进行jest.fn(...)noop 但不会将间谍恢复到原始实现。这特别影响每个测试套件在模拟模块中提供的间谍jest.mock,但仍然不会恢复全局间谍。由于这种行为很少需要,jest.restoreAllMocks()或者restoreMocks配置选项通常是可取的。如果需要jest.fn(...)重置实现,mockReset或者mockImplementation可以专门为此间谍完成。


推荐阅读