Jest · Unit tests that survive refactors
What is the difference between the jsdom and node test environments?
Short answer
jsdom emulates a browser DOM inside Node but has no real layout or navigation. The node environment has no document and is faster and closer to a server runtime.
Both environments run on Node. The difference is the set of globals Jest injects. jsdom provides window, document, HTMLElement and event APIs, so React Testing Library can mount components. The node environment provides none of that and behaves more like a production server process.
What jsdom does and does not give you
- It parses HTML, supports DOM traversal, events and forms
- It does not calculate layout, so
getBoundingClientRectreturns zeros - It does not perform real navigation or load subresources
- It implements a subset of browser APIs, not all of them
- It is slower to start than the node environment
export default {
projects: [
{
displayName: "dom",
testEnvironment: "jsdom",
testMatch: ["<rootDir>/src/components/**/*.test.tsx"],
},
{
displayName: "server",
testEnvironment: "node",
testMatch: ["<rootDir>/src/server/**/*.test.ts"],
},
],
};A test that passes in jsdom can still fail in a real browser because of layout, focus, scrolling, CSS or unsupported APIs. Use jsdom for logic and component interaction, and use a real browser for visual behaviour, responsive layout and cross-browser concerns.
typeof window, jsdom will take the browser path. That can be useful for component tests but misleading for a server module, which is another reason to keep server tests in the node environment.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why does getBoundingClientRect return zero in jsdom?
- 2Can jsdom run real navigation?
- 3How do you choose an environment per package?
- 4When do you need a real browser instead of jsdom?
Say it in the interview
jsdom gives Node a browser-like DOM, so I can render components and dispatch events. It does not do layout, real navigation or subresource loading, and it implements only part of the browser API. The node environment is faster and closer to a server process but has no document. I split them by project, and I use a real browser for anything that depends on layout or rendering.
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.