首页 > 解决方案 > 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.logtestTeardown和结束测试,并且日志以正确的顺序发生:测试日志,然后是拆卸日志。但是,如果我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 的设置/拆卸功能甚至与测试在同一过程中运行吗?

标签: javascriptnode.jsjestjs

解决方案


不,开玩笑的 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']
};

推荐阅读