开玩笑全球拆解运行测试完成之前?

问题描述 投票:1回答:1

我想确保我的应用进行了我所有的玩笑测试都运行正常后销毁,但我遇到了一些非常奇怪的行为试图用玩笑的全球拆解的配置价值。

这里的情况:我的应用程序创建一个数据库连接。它也有关闭数据库连接的destroy方法。这工作。

我有一个单一的测试启动服务器,运行对数据库连接的查询。在我的全球拆卸功能,我称之为app.destroy(),但该过程将挂起。

如果我注释掉在全球拆解功能destroy看涨和看跌app.destroy()在我的测试查询后,玩笑不挂和关闭喜欢它应该。我也可以把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,然后检查它的拆解处理,但它是undefined。不要玩笑的安装/拆卸功能,即使是在同一个进程中的测试得到运行?

javascript node.js jestjs
1个回答
1
投票

没有,开玩笑globalSetup和globalTeardown文件未必会在同一进程中你的测试运行。这是因为笑话parallelises您的测试和运行在单独的进程中每个测试文件,但只有一个被组合组的测试文件的全局设置/拆卸阶段。

您可以使用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']
};
© www.soinside.com 2019 - 2024. All rights reserved.