Jest beforeAll() 在多个测试文件之间共享 [英] Jest beforeAll() share between multiple test files
问题描述
我有一个 Node.js 项目,正在使用 Jest 进行测试.我有几个具有相同设置要求的测试文件.以前,所有这些测试都在一个文件中,所以我只有一个 beforeAll(...)
来执行通用设置.现在,随着测试分成多个文件,似乎我必须将 beforeAll(...)
代码复制/粘贴到每个文件中.这似乎不雅 - 有没有更好的方法来做到这一点,理想情况下,我可以只编写一次 beforeAll(...)
/setup 逻辑,然后从多个测试文件中要求"它?请注意,我的测试套件中还有其他测试不需要此设置功能,因此我不想让所有我的测试运行此设置(只是测试文件的特定子集).
I have a Node.js project that I'm testing using Jest. I have several test files that have the same setup requirement. Previously, all these tests were in one file, so I just had a beforeAll(...)
that performed the common setup. Now, with the tests split into multiple files, it seems like I have to copy/paste that beforeAll(...)
code into each of the files. That seems inelegant - is there a better way to do this, ideally where I can just write my beforeAll(...)
/setup logic once, and "require" it from multiple test files? Note that there are other tests in my test suite that don't require this setup functionality, so I don't want to make all my tests run this setup (just a particular subset of test files).
推荐答案
如果您使用 Jest >=20,您可能需要考虑为测试创建自定义 jest-environment
需要这种通用设置.这将是一个扩展 jest-environment-node
或 jest-environment-jsdom
的模块,并实现 async setup()
, async teardown()
和 async runScript()
来完成这个设置工作.
If you're using Jest >=20, you might want to look into creating a custom jest-environment
for the tests that require this common setup. This would be a module that extends either jest-environment-node
or jest-environment-jsdom
, and implements async setup()
, async teardown()
, and async runScript()
to do this setup work.
然后,您可以向需要此设置的文件添加 @jest-environment my-custom-env
指令.
You can then add a @jest-environment my-custom-env
directive to those files that require this setup.
请参阅 Jest 配置文档以了解 testEnvironment代码>
有关如何设置的详细信息;那里有一个简单的例子.
See the Jest config docs for testEnvironment
for details on how to set this up; there's a simple example there.
这篇关于Jest beforeAll() 在多个测试文件之间共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!