如何在 JEST 中关闭模块重新加载?

时间:2021-02-21 09:52:37

标签: node.js express testing jestjs supertest

我正在使用 Jest 测试用 express.js 编写的 express REST api 和使用 ts-jest 的打字稿。我的问题是 Jest 在每个测试套件中加载应用模块(express),它只持续 3-4 秒,但有大约 80 个测试套件,每个包含多个测试用例。

我的第一个想法是从全局 afterAll() 函数中删除 jest.resetModules(),但它没有帮助。有没有其他方法可以改变这种行为,或者它是设计特性?

setup.ts

import { sequelize } from '../src/db/models'
import seeds from '../src/db/seeders/test'

// multiple mocks of services
jest.mock('../some/custom/module/mocks')


beforeAll(async () => {
    await sequelize.sync({ force: true }) // basically drop db and create clean one
    await seeds() // seed database with data
})

afterAll(async () => {
    jest.clearAllMocks()
    // jest.resetModules() //! This line was removed
    await sequelize.close()
    global.gc()
})

jest.setTimeout(10000)

全局.ts

import { createJwt } from '../src/utils/authorization'

export default async () => {
// create some acces tokens and add to process.env
    process.env.jwttoken = await createJwt({ uid: 1 }, { audience: 'users' })
}

jest.config.js

module.exports = {
transform: {
    '^.+\\.ts?$': 'ts-jest'
},
roots: [
    '<rootDir>/tests/'
],
moduleFileExtensions: [
    'ts',
    'js'
],
setupFilesAfterEnv: [
    '<rootDir>/tests/setup.ts'
],
globalSetup: '<rootDir>/tests/global.ts',
testEnvironment: 'node'
}

示例测试

import supertest from 'supertest'
import app from '../../../../../src/app'

describe(`[GET] ${endpoint(':id')})`, () => {
const request = supertest(app).  // every time jest hits this line in test, it load app again

it('no authorization token | code 401', async () => {
    const response = await request.get('/something')
        .set('Content-Type', 'application/json')
    expect(response.status).toBe(401)
})

启动脚本

POSTGRESQL_URL=postgresql://postgres:root@127.0.0.1:5432/database JWT_SECRET=secret node --expose-gc \"./node_modules/jest/bin/jest.js\" --runInBand --passWithNoTests --logHeapUsage

0 个答案:

没有答案