在Jest中进行每次测试之前运行全局测试设置 [英] Running a global test setup before each test in Jest

查看:102
本文介绍了在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(() => {
   ...
});

这篇关于在Jest中进行每次测试之前运行全局测试设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆