Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup jsdom when working with jest

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!

like image 860
Gal Ziv Avatar asked Dec 05 '16 09:12

Gal Ziv


People also ask

Does Jest use Jsdom?

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.

What does Jest environment Jsdom do?

By default, jest uses the node testEnvironment. This essentially makes any tests meant for a browser environment invalid. jsdom is an implementation of a browser environment, which supports these types of UI tests.

Do I need to install Jsdom?

jsdom is a pure JavaScript implementation of the DOM and browser APIs that runs in node. If you're not using Jest and you would like to run your tests in Node, then you must install jsdom yourself. There's also a package called global-jsdom which can be used to setup the global environment to simulate the browser APIs.

What version of Jsdom does Jest use?

Jest v25 by default uses JSDOM 15 to support Node 8.


1 Answers

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' });
like image 62
Rick Hanlon II Avatar answered Sep 30 '22 18:09

Rick Hanlon II