javascript - Jest 全球拆解在测试完成之前运行?
问题描述
我试图确保在我的所有 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
在测试中设置 a 然后在拆解处理程序中检查它,但它是undefined
. Jest 的设置/拆卸功能甚至与测试在同一过程中运行吗?
解决方案
不,开玩笑的 globalSetup 和 globalTeardown 文件不一定与您的测试在同一进程中运行。这是因为 jest 将您的测试并行化并在单独的进程中运行每个测试文件,但是对于组合的测试文件集只有一个全局设置/拆卸阶段。
您可以使用setupFiles
添加与每个测试文件一起运行的文件。在setupFiles
文件中,您可以放置:
afterAll(() => app.destroy());
你的笑话配置只是
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']
};
推荐阅读
- r - rowSums(out_pathway) 中的错误:“x”必须是至少二维的数组
- javascript - Typo 不想在 ios 和 android 项目上链接
- actionscript-3 - AS3:拖放对象的触摸事件问题
- css - JavaFX - 不同的默认 CSS 窗口和 linux?
- laravel - laravel 验证不适用于 Auth
- paraview - paraview:加载共享库时出错:libQt5Core.so.5:无法打开共享对象文件:没有这样的文件或目录
- asp.net - 具有不变名称“Oracle.DataAccess.Client”的 ADO.NET 提供程序未注册或无法加载
- php - 了解查询并将其转换为 Oracle SQL
- c# - 使用 Xelement 时如何换行
- python - 如何自动裁剪徽标图像的背景(最好是任何颜色)