Jest · Unit tests that survive refactors
What is testEnvironment and when do you change it?
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.
/**
* @jest-environment jsdom
*/
test("renders a button", () => {
document.body.innerHTML = "<button>Save</button>";
expect(document.querySelector("button")?.textContent).toBe("Save");
});Ways to set it
testEnvironmentin the Jest config for the default- A
@jest-environmentdocblock at the top of a file projectswhen a repo has both browser and server packagesjest-environment-jsdominstalled 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.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1How do you set the environment for a single test file?
- 2Why is a global jsdom default a problem for server code?
- 3What does jsdom not implement?
- 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.