使用 jest 时如何设置 jsdom [英] How to setup jsdom when working with jest

查看:43
本文介绍了使用 jest 时如何设置 jsdom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 AVA 迁移到 Jest.在AVA中可以设置ava.setup,在其中设置jsdom环境.例如,创建 DOM 结构并进行必要的 polyfills (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 setting 指向在所有测试运行之前执行的文件.

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屋!

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