问题描述
我正在使用 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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)