使用Jest时如何设置jsdom [英] How to setup jsdom when working with jest
问题描述
我正在尝试从AVA迁移到Jest.在AVA中,您可以设置ava.setup
,在其中设置jsdom
环境.例如,创建DOM结构并进行必要的polyfill(localStorage).
I'm trying to migrate from AVA to Jest. In AVA you can set ava.setup
, in which you set the jsdom
environment. For example, creating the DOM structure and doing necessary polyfills (localStorage).
我如何在Jest中做到这一点?目前,我在每个测试套件中都使用beforeEach
,这似乎并不是最好的解决方案.
How do I accomplish that in Jest? Currently, I'm using beforeEach
in each test suite, which doesn't feel like the best solution.
提前谢谢!
推荐答案
好问题.
Jest实际上附带了jsdom
和已经配置的环境.您可以使用testEnvironment
设置覆盖它
Jest actually ships with jsdom
and the environment already configured. You can override it with the testEnvironment
setting.
但是,如果您需要设置环境的更多方面,则可以使用setupTestFrameworkScriptFile
设置指向在所有测试运行之前执行的文件.
If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile
setting to point to a file that executes before all of your tests run.
例如,如果需要window.yourVar
在所有测试的窗口中都可用,则可以将其添加到package.json
中:
For example, if you need window.yourVar
to be available on the window for all your tests, you would add this to your package.json
:
"jest": {
"setupTestFrameworkScriptFile": "tests/setup.js"
}
在tests/setup.js中:
And in tests/setup.js:
Object.defineProperty(window, 'yourVar', { value: 'yourValue' });
这篇关于使用Jest时如何设置jsdom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!