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

查看:30
本文介绍了在 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 配置文件,并注意到了一些认为可能有效的配置:globalSetupsetupFiles,但它们似乎只运行一次(在测试运行的最开始时).就像我说的,我需要在我的测试文件中的每个"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中,可以直接写:

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

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

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

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