jest: configuring test environments

2021-05-04

 | 

~2 min read

 | 

345 words

By default, Jest runs tests in a “browser-like” environment using jsdom. This, however, is configurable. For example, if you’re building a node application and/or do not need access to the dom (i.e., a unit test on a pure function), you can specify a different environment, like node. Alternatively, you can define a custom environment.

More details are here, but below are some simple(r) examples of how this might be used.

Add testEnvironment to jest.config.js

If we wanted to use the node environment, we could have a config file with the following testEnvironment:

jest.config.js
module.exports = {
  testEnvironment: "jest-environment-node",
}

Alternatively, if we wanted to be explicit we could set jsdom like so:

jest.config.js
module.exports = {
  testEnvironment: "jest-environment-jsdom",
}

Where do these names come from? They’re node modules that are shipped by default with jest (it’s a dependency of jest-config, which itself is a dependency of jest-cli).

Add a @jest-environment doc block

Note: The docs suggest that this approach works, however, it did not work in my experience. Perhaps a better approach is to use multiple configurations and define the environment in the configuration file.

/**
 * @jest-environment jsdom
 */

test('use jsdom in this test file', () => {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});
/**
 * @jest-environment node
 */

test('do not use jsdom in this test file', () => {
  console.log(window); // this will fail as node doesn't have a window object
});

Wrap Up

It’s good to know that you can modify the environment to be what you need, though I’ll admit, this is one area where the Jest documentation appears to be lacking - particularly in the doc blocks area.

I’m glad I’ve worked through a few examples so that I’ll know how to make it work as I need!

The key point, however, is that within jest.config files, we can specify the environment. We can use jsdom (the default) or node out of the box. We can also import other environments from a package registry like npm - there are lots.


Related Posts
  • Jest: How to configure Jest for testing Javascript applications


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!