23

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!

jacefarm
  • 6,747
  • 6
  • 36
  • 46
Gal Ziv
  • 6,890
  • 10
  • 32
  • 43

2 Answers2

40

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' });
mhchia
  • 139
  • 1
  • 8
Rick Hanlon II
  • 20,549
  • 7
  • 47
  • 53
10

Update 2022. Version 28 does not ship jsdom by default anymore:

As of Jest 28 "jsdom" is no longer shipped by default, make sure to install it separately.

You'll need to install jsdom manually:

# npm
npm install -D jest-environment-jsdom
# yarn
yarn add jest-environment-jsdom

credit to: https://stackoverflow.com/a/72013609/7089048

David
  • 425
  • 4
  • 9