skip to content

Setup and Configuration

The jest.config options that matter — testEnvironment, setupFiles versus setupFilesAfterEnv, transforms, moduleNameMapper, and multi-project setups. Asked because most 'Jest is broken' problems are really transform or module-resolution problems.

on this pageshow

explore

questions

6

In Jest 30, what is the default testEnvironment, and what do you change so a React component test can use document?

level: juniorimportance: must knowfreq 62%

answer

  1. server default, no DOM
  2. separate package since Jest 28
  3. config key or per-file docblock
  4. one environment per test file

basics

~10 s

Jest 30 defaults testEnvironment to node, so document and window do not exist. Install jest-environment-jsdom, then set testEnvironment: 'jsdom' in the config or add a @jest-environment jsdom docblock to that test file.

solid answer

~50 s

`testEnvironment` defaults to `node`: each test file runs in a Node context with no DOM, so a component test that touches `document` fails with `ReferenceError: document is not defined`. For DOM tests you switch to `jsdom`, a simulated browser built on the jsdom library. Jest stopped bundling `jest-environment-jsdom` in Jest 28, so you install it yourself; if you set `jsdom` without it, Jest stops before any test with a validation error saying the environment cannot be found. You can set `testEnvironment: 'jsdom'` for the whole config, or keep `node` and opt single files in with a `/** @jest-environment jsdom */` docblock at the top of the file, which suits a package that mixes server and component tests. Jest creates a fresh environment for every test file, so globals one file creates are not visible in another.

code

javascript · 9 lines
javascript
// jest.config.js
const {defineConfig} = require('jest');

module.exports = defineConfig({
  testEnvironment: 'jsdom',
  testEnvironmentOptions: {
    url: 'https://app.test/',
  },
});

go deeper

for a junior

Know that the default is node, why document is undefined there, and the two ways to switch a file or a whole config to jsdom.

for a middle

Explain that every test file gets its own environment instance, that jsdom is a separately installed package, and what testEnvironmentOptions such as url control.

for a senior

Diagnose environment-shaped failures: a missing environment package, a dependency resolving a browser build under jsdom, and a suite slowed by running server tests under jsdom.

for a principal

Decide how a monorepo assigns environments, usually node by default with jsdom only where components render, and when layout-dependent checks must move to a real browser.

## What `testEnvironment` decides Every Jest test file runs inside a **test environment**: an object that builds the global scope the file sees and tears it down afterwards. Jest creates **one environment instance per test file**, calls its `setup` before the file runs and its `teardown` after it, so a global that one file creates is not visible to the next. The `testEnvironment` config key names the environment class to use, and `testEnvironmentOptions` passes options to it. Jest has two built-in environments: - `node`, provided by `jest-environment-node`, which comes with Jest. - `jsdom`, provided by `jest-environment-jsdom`, which you install separately. ## The default is `node` In Jest 30 the default is `node`. A test file gets Node's globals, such as `process`, `Buffer` and the timer functions, but there is no `window`, no `document` and no DOM classes. That is the right default for server code, utilities and anything that never renders, and it is what you want for an API package. The moment a test renders a React component or calls a DOM API, the default fails: ```plaintext ReferenceError: document is not defined ``` The error is not a bug in the component. It says the file is running in an environment that has no DOM. ## Switching to `jsdom` 1. **Install `jest-environment-jsdom`** as a dev dependency. It has not been bundled with Jest since Jest 28, and the Jest 30 release of it uses JSDOM v26. 2. **Choose the scope**: set `testEnvironment: 'jsdom'` in the config, or opt single files in with a docblock. 3. **Tune it if needed** with `testEnvironmentOptions`: `url` sets `window.location` (default `http://localhost`), `userAgent` sets the user agent, and `customExportConditions` controls how package `exports` maps are resolved. Jest turns the short name `jsdom` into `jest-environment-jsdom`, and for other names it also tries the `jest-environment-` prefix, so `testEnvironment` can name a package or a path to a custom environment. If step 1 is skipped, Jest stops before running anything: ```plaintext Test environment jest-environment-jsdom cannot be found. Make sure the testEnvironment configuration option points to an existing node module. As of Jest 28 "jest-environment-jsdom" is no longer shipped by default, make sure to install it separately. ``` ## Config key or docblock? | Where you set it | What it covers | Use it when | |---|---|---| | `testEnvironment` in the config | every test file of that config or project | the whole package renders components | | `/** @jest-environment jsdom */` at the top of a file | that one file | one package mixes server tests and DOM tests | | a different `testEnvironment` per entry in `projects` | each project | a monorepo with a web package and an API package | The docblock works at **file** granularity. There is no way to switch the environment for one `test` inside a file, because the environment is built before the file's code runs. For the same reason, a setup file cannot change it: `setupFiles` already runs inside the chosen environment. ## What `jsdom` gives you, and what it does not - **It gives** a DOM tree, `window`, `document`, events and the many web APIs jsdom implements in JavaScript, which is enough to render a component and query or click it. - **It does not lay out pages.** jsdom has no rendering engine, so sizes and positions are not computed; checks that depend on real layout or paint belong in a runner that drives a real browser. - **It resolves packages differently.** The jsdom environment uses the `browser` export condition, while the node environment uses `node` and `node-addons`. A dependency with an `exports` map can therefore load a different file under jsdom, sometimes an ESM-only browser build that then fails to load. `testEnvironmentOptions.customExportConditions` overrides the list. - **It is heavier than `node`.** Building a DOM for every file costs time, so keeping server-only files on `node` keeps a large suite faster. ## Mistakes interviewers listen for - Assuming Jest picks `jsdom` by itself when a test touches the DOM. It never switches on its own; the default stays `node`. - Installing the `jsdom` library and expecting that to be enough. Jest looks for the `jest-environment-jsdom` package. - Trying to create `window` in a setup file instead of choosing an environment. - Putting the whole monorepo on `jsdom` because one package needs it, which slows down every server test.

  • Why might a dependency that loads fine in a node-environment test fail to load in a jsdom-environment test?
    The two environments resolve package `exports` maps with different conditions: jsdom uses `browser`, node uses `node` and `node-addons`. A package can map `browser` to an ESM-only build, which then fails to load from CommonJS test code. Override the list with `testEnvironmentOptions.customExportConditions`, or let that package be transformed.
  • Can one test inside a file run under jsdom while the other tests in that file stay on node?
    No. The environment is created per test file, before any of the file's code runs, and the `@jest-environment` docblock applies to the whole file. Split the DOM tests into their own file, or move them into a project whose `testEnvironment` is `jsdom`.

  • Jest defaults to jsdom, so document is always available in a test.
  • Jest switches to jsdom on its own when a test touches the DOM.
  • jest-environment-jsdom ships inside the jest package, so nothing needs installing.
  • A @jest-environment docblock can switch the environment for a single test inside a file.
  • Under the node environment all test files share one global object.
open as a page

In Jest 30, what is the difference between setupFiles and setupFilesAfterEnv, and what can code in each one use?

level: middleimportance: must knowfreq 58%

basics

~20 s

Both run before every test file. setupFiles runs first, inside the environment but before the test framework is installed, so expect, test and the hooks are undefined; setupFilesAfterEnv runs next and can call expect.extend or register afterEach.

open as a page

In a Jest test suite, why does importing '@/lib/price' or a .css file fail when the app builds fine, and how does moduleNameMapper fix it?

level: middleimportance: should knowfreq 50%

basics

~10 s

Jest resolves modules itself and reads neither the tsconfig paths nor the bundler's aliases and CSS loaders. moduleNameMapper maps request regexes to replacements, such as '^@/(.*)$' to '<rootDir>/src/$1' and '\.css$' to a stub module.

open as a page

In Jest 30, how does the transform option decide which tool compiles a TypeScript or JSX test file?

level: middleimportance: should knowfreq 45%

basics

~20 s

transform maps file-path regexes to transformers. With no transform key, Jest 30 uses babel-jest for .js, .jsx, .ts and .tsx files; once you set transform, that default is gone, so you list babel-jest, ts-jest or @swc/jest yourself.

open as a page

In a Jest 30 suite, why does a test that imports an ESM-only package from node_modules fail to load, and how do you fix it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

transformIgnorePatterns defaults to skipping /node_modules/, so the package's import and export syntax is never compiled and loading it as CommonJS fails. Allowlist it, for example '/node_modules/(?!(package-a)/)', or on Node 24.9+ run Jest with --experimental-vm-modules to require() it natively.

open as a page

In a Jest 30 monorepo with a jsdom React package and a node API package, how do you run both through one projects config, and what must stay at the root?

level: seniorimportance: should knowfreq 32%

basics

~20 s

projects lists paths, globs or inline config objects, and each entry becomes its own project with its own rootDir, testEnvironment, transform and moduleNameMapper. Run-wide options such as reporters, maxWorkers and coverageThreshold belong only in the root config.

open as a page