Jest · Unit tests that survive refactors

What is testEnvironment and when do you change it?

MediumtestEnvironmentjsdomnodeUpdated Oct 2026
Quiz this track

Short answer

testEnvironment selects the globals available to a test file. Use jsdom for code that needs a DOM and node for server code, and scope the choice per file or project when needs differ.

The environment decides what document, window and other globals exist. It is not a browser. Choosing the wrong one either gives you a missing document or adds overhead and misleading globals that your production runtime does not have.

ts
/**
 * @jest-environment jsdom
 */

test("renders a button", () => {
  document.body.innerHTML = "<button>Save</button>";
  expect(document.querySelector("button")?.textContent).toBe("Save");
});
The docblock overrides the environment for one file without changing the global config.

Ways to set it

  • testEnvironment in the Jest config for the default
  • A @jest-environment docblock at the top of a file
  • projects when a repo has both browser and server packages
  • jest-environment-jsdom installed explicitly in recent Jest versions

If most files are server-side logic, default to node and opt into jsdom only for component tests. A global jsdom default makes every test pay for DOM setup and can hide accidental browser API usage in server code.

jsdom is not a real browser and does not implement layout, real navigation or many platform APIs. Tests that depend on those need a real browser runner, not a different Jest environment.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1How do you set the environment for a single test file?
  2. 2Why is a global jsdom default a problem for server code?
  3. 3What does jsdom not implement?
  4. 4How do projects help in a monorepo?

Say it in the interview

testEnvironment controls which globals exist. I default to node for server-side code and use jsdom only where a DOM is required, either through config or a per-file docblock. A global jsdom default slows everything down and can mask accidental browser API use in server code. jsdom is still not a browser, so anything depending on layout or real navigation needs an end-to-end tool.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.