我试图确保我的应用程序在我的所有 Jest 测试运行后被正确销毁,但是我在尝试使用 Jest 的全局拆卸配置值时遇到了一些非常奇怪的行为。
情况如下:我的应用程序创建了一个数据库连接。它还有一个 destroy
关闭数据库连接的方法。这行得通。
我有一个启动服务器的测试,对数据库连接运行查询。在我的全局拆解函数中,我调用 app.destroy()
,但进程挂起。
如果我注释掉 destroy
调用全局拆解函数并放入 app.destroy()
在查询后的测试中,Jest 不会像预期的那样挂起并关闭。我也可以放afterAll(() => app.destroy())
在我的测试文件中,一切正常。
这是我的jest.config.js
module.exports = {
testEnvironment: 'node',
roots: [
'<rootDir>/src'
],
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx',
'json',
'node'
],
globalSetup: '<rootDir>/src/testSetup.ts',
globalTeardown: '<rootDir>/src/testTeardown.ts'
};
这是测试(它目前是应用程序中唯一的测试):
import app from '../..';
describe('User router', () => {
it('Should respond with an array of user objects', async () => {
await app.models.User.query();
});
});
这是
<rootDir>/src/testTeardown.ts
中的全局拆解:import app from './index';
module.exports = async function testTeardown() {
await app.destroy();
};
使用上面的代码,该过程在测试完成后挂起。我试过添加
console.log
至testTeardown
测试结束,日志以正确的顺序发生:测试日志,然后是拆解日志。但是,如果我移动 app.destroy()
在我的测试中它完美地工作:import app from '../..';
describe('User router', () => {
it('Should respond with an array of user objects', async () => {
await app.models.User.query();
await app.destroy();
});
});
这也有效:
import app from '../..';
afterAll(() => app.destroy());
describe('User router', () => {
it('Should respond with an array of user objects', async () => {
await app.models.User.query();
});
});
为什么会这样?
也只是为了大便和咯咯笑,我尝试设置
global._app
在测试中,然后在拆卸处理程序中检查它,但它是 undefined
. Jest 的设置/拆卸功能甚至与测试在同一过程中运行吗?
最佳答案
不, Jest globalSetup 和 globalTeardown 文件不一定与您的测试在同一进程中运行。这是因为 jest 将您的测试并行化并在单独的进程中运行每个测试文件,但是对于组合的测试文件集只有一个全局设置/拆卸阶段。
您可以使用 setupFiles
添加一个与每个测试文件一起运行的文件。在 setupFiles
你可以放的文件:
afterAll(() => app.destroy());
你的 Jest 配置只是
module.exports = {
testEnvironment: 'node',
roots: [
'<rootDir>/src'
],
transform: {
'^.+\\.tsx?$': 'ts-jest'
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx',
'json',
'node'
],
setupFiles: ['<rootDir>/src/testSetup.ts']
};
关于javascript - Jest 全局拆解在测试完成之前运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54488148/