How to setup jsdom when working with jest

你说的曾经没有我的故事 提交于 2020-07-04 07:51:28

问题


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).

How do I accomplish that in Jest? Currently, I'm using beforeEach in each test suite, which doesn't feel like the best solution.

Thanks in advance!


回答1:


Great question.

Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment 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.

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"
}

And in tests/setup.js:

Object.defineProperty(window, 'yourVar', { value: 'yourValue' });


来源:https://stackoverflow.com/questions/40970780/how-to-setup-jsdom-when-working-with-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!