在Jest中进行每次测试之前运行全局测试设置

在Jest中进行每次测试之前运行全局测试设置

问题描述:

我正在尝试在Jest测试套件中的每个测试之前执行测试设置功能.我知道我可以使用beforeEach在单个测试文件中完成此操作,但是我想全局地对所有我的测试文件进行此操作,而无需显式修改每个单个文件.

I'm trying to have a test setup function executed before each single test in my Jest test suite. I know that I can use beforeEach to accomplish this within a single test file, but I want to do it globally for all my test files without having to explicitly modify each single file.

我查看了 jest配置文件,并注意到了几个认为可行的配置: globalSetup setupFiles ,但它们似乎已在运行仅一次(在测试运行的最开始).就像我说的那样,我需要在测试文件中的每个" it块之前运行它.

I looked into the jest configuration file, and noticed a couple of configs that thought could have worked: globalSetup and setupFiles, but they seem to be run only once (at the very beginning of the test run). Like I said, I need it to be run before "each" it block in my test files.

这可能吗?

您可以使用setupFilesAfterEnv(它取代了setupTestFrameworkScriptFile,从jest版本24.x开始弃用),它将在每次测试之前运行

You could use setupFilesAfterEnv (which replaces setupTestFrameworkScriptFile, deprecated from jest version 24.x) which will run before each test

// package.json
{
  // ...
  "jest": {
    "setupFilesAfterEnv": ["<rootDir>/setupTests.js"]
  }
}

setupTests.js中,您可以直接编写:

And in setupTests.js, you can directly write:

global.beforeEach(() => {
  ...
});

global.afterEach(() => {
   ...
});