Jest 27 ๐ DOM Environment โ jsdom, happy-dom, and the window.location spec change
Jest does not run your test in a browser. It runs the test in a Node process, and then the environment โ a small object the runner hands to each test file โ decides what globals that file sees. With testEnvironment: 'node' the global is Node’s: process, Buffer, setImmediate, and no document. With testEnvironment: 'jsdom' the global is a freshly constructed JSDOM instance: window, document, history, location, localStorage, and a document.body that React can render into.
That single configuration key has moved twice in Jest’s recent history, and both moves broke suites. Jest 26 defaulted every file to jsdom, which meant a pure utility test paid for a DOM it never used. Jest 27 flipped the default to node โ a breaking change, announced as such, and the reason a suite that upgraded from 26 to 27 suddenly fails with document is not defined. Jest 28 then removed the bundled environments entirely, so jest-environment-jsdom became a package you install rather than a name you reference.
The third thread in this chapter is a spec-alignment change inside jsdom itself, and it is the one that produced the most confused debugging sessions. Every codebase carried the same snippet โ delete window.location; window.location = { href: '...' } โ and it stopped working when jsdom aligned its Window implementation with the HTML specification, where window.location is an own, non-configurable, getter-only property. There is no monkey-patch that restores the old behaviour, and the workarounds that remain are narrower and more explicit.
This chapter covers the environment layer from the outside in. The first section is the choice itself โ node, jsdom, or happy-dom, how the config and the docblock interact, and how testEnvironmentOptions replaced testURL. The second section is what jsdom actually implements and where the gaps are. The third is happy-dom, its Jest environment package, and the trade-offs. The fourth is the window.location binding โ the spec rule behind the break and the four workarounds that still work.
Key point: The environment is a per-file global object, not a browser and not a shared context โ each test file gets its own instance, its own document, and its own window, so nothing carries between files and the DOM is gone the moment the file finishes. Every gap you hit is a gap in that object, not a bug in Jest, and the window.location break is the clearest example: the specification says that binding is unforgeable, so the fix is to stop replacing it and change the URL through history.pushState instead.
Why the DOM environment exists
The Node has no document problem. Jest’s runner is Node, and Node has no document, no window, and no localStorage. A component test needs all three, so the environment layer stands between the runner and the test: it constructs a JSDOM instance, copies its globals onto the test file’s globalThis, and tears the whole thing down when the file ends. Everything a DOM test can do is something that layer chose to expose.
The default-flip problem. Jest 26 defaulted to jsdom for every file. That made the first version of a suite frictionless and the tenth version slow, because a test of a date-formatting helper was constructing an entire DOM before it ran a single assertion. Jest 27 changed the default to node and listed it as a breaking change. Upgrading meant either setting testEnvironment: 'jsdom' explicitly or annotating each file that needs a DOM โ and the error you get for forgetting is ReferenceError: document is not defined, which points at the test rather than at the configuration.
The packaging problem. Jest 28 went further and stopped shipping the environments in the main package. jest-environment-jsdom and jest-environment-node became separate packages with their own versions and their own release cadence, and the reason is the jsdom version: the environment is bound to a specific jsdom major, and letting Jest’s major dictate it kept suites pinned to old DOM implementations. The consequence is that a fresh Jest 28+ install with testEnvironment: 'jsdom' fails until jest-environment-jsdom is installed as well.
The fidelity problem. jsdom is a DOM implementation, not a browser. It parses HTML, builds a tree, implements events, and implements history and location well enough to run a router. It has no layout engine, so getBoundingClientRect() returns a rectangle of zeros and offsetWidth is 0; it has no painting, so nothing is ever off-screen; it does not implement scrollIntoView at all, and it implements matchMedia, ResizeObserver, and IntersectionObserver not at all. A test that depends on any of those is not testing the application โ it is testing the polyfill you wrote into the setup file.
The performance problem. A JSDOM instance is expensive to construct: parsing a document, setting up the window proxy, installing a hundred interfaces. That cost is paid once per test file, and a suite of 400 files on 4 workers pays it 400 times. It is usually the single largest item in a suite’s startup, which is precisely why happy-dom exists and why testEnvironment: 'node' for non-DOM files is a real speedup rather than a preference.
The spec-alignment problem. jsdom follows the Web IDL definitions, and the HTML specification marks window.location โ and document.location โ as [LegacyUnforgeable]. In practice that means window.location is an own accessor property of window with configurable: false. When jsdom implemented that rule properly, every delete window.location snippet in every codebase stopped working, and the failure is a TypeError rather than a silent no-op.
The trade-off. An environment that is not a browser buys speed and determinism and costs fidelity. A DOM test that passes in jsdom is evidence that the component renders the right markup and responds to the right events; it is not evidence that the layout is correct, that the element is on screen, or that a stylesheet applied. The discipline is to keep the assertions inside the fidelity the environment actually provides โ roles, text, attributes, and declared styles โ and to move anything that needs layout into a real-browser test.
a. Choosing an environment โ node, jsdom, and per-file annotation
The environment is set globally in the config and overridden per file with a docblock. The docblock wins, which makes it the right tool for the handful of files that differ from the suite.
// jest.config.js
module.exports = {
// Jest 27+ default. No DOM. Plain Node globals.
testEnvironment: 'node',
// Needed from Jest 28 on: the jsdom environment is a separate package.
// npm i -D jest-environment-jsdom
};
// src/Counter.test.tsx โ one file opts into the DOM
/**
* @jest-environment jsdom
*/
import { render, screen } from '@testing-library/react';
test('renders', () => {
render(<Counter count={1} />);
expect(screen.getByText('1')).toBeInTheDocument();
});
The pragma that goes with it is @jest-environment-options, which takes a JSON object and merges it into that file’s environment construction. It is how a single file gets a different URL, or pretendToBeVisual, without touching the config for the rest of the suite.
/**
* @jest-environment jsdom
* @jest-environment-options {"url": "https://shop.example.com/cart"}
*/
test('reads the query string', () => {
// location reflects the URL this environment was constructed with
expect(window.location.pathname).toBe('/cart');
expect(window.location.origin).toBe('https://shop.example.com');
});
The global equivalent is testEnvironmentOptions, and it replaced the old testURL option in Jest 27. A suite migrating from Jest 26 with testURL: 'http://localhost' has to move that value into the nested object, because the flat option is gone and leaving it in place produces a validation error rather than a silent fallback.
// jest.config.js โ Jest 27 style
module.exports = {
testEnvironment: 'jsdom',
testEnvironmentOptions: {
url: 'http://localhost:3000/', // was: testURL
pretendToBeVisual: true, // requestAnimationFrame
},
};
A mixed suite is written as multiple projects, one per environment, each with its own testMatch. This is the pattern worth adopting early, because it lets a component project and a Node project share a single jest invocation and a single coverage report while paying for jsdom only where it is used.
// jest.config.js โ two environments in one run
module.exports = {
projects: [
{
displayName: 'unit',
testEnvironment: 'node',
testMatch: ['<rootDir>/src/lib/**/*.test.ts'],
},
{
displayName: 'components',
testEnvironment: 'jsdom',
testEnvironmentOptions: { url: 'http://localhost/' },
testMatch: ['<rootDir>/src/components/**/*.test.tsx'],
},
],
};
b. jsdom โ what it implements and where it stops
The Jest jsdom environment constructs its JSDOM with pretendToBeVisual: true, which is what makes requestAnimationFrame and cancelAnimationFrame present. Without it a component that schedules a frame throws on mount, and the error message names requestAnimationFrame rather than the environment flag.
// present because the Jest jsdom environment enables pretendToBeVisual
window.requestAnimationFrame((t) => {
// t is a DOMHighResTimeStamp, and the callback runs on a timer
expect(typeof t).toBe('number');
});
Events, history, and location are implemented well enough for a router. This is the part that surprises people coming from a browser-less test runner that stubs location entirely โ history.pushState genuinely updates location.pathname, location.search, and location.hash, and a popstate listener genuinely receives an event.
window.history.pushState({}, '', '/orders?page=2');
expect(window.location.pathname).toBe('/orders');
expect(window.location.search).toBe('?page=2');
window.location.hash = '#items';
expect(window.location.hash).toBe('#items'); // hash changes are implemented
Assignment to href is the opposite case. Navigating the document is not implemented, and jsdom reports it through the virtual console: Error: Not implemented: navigation (except hash changes). Jest prints that as a console error inside the test output, so a suite that stubs a redirect by assigning location.href looks like it is failing when it is only warning.
// prints "Not implemented: navigation (except hash changes)"
window.location.href = '/checkout';
// the hash assignment above is the exception: hash changes do work
window.location.hash = '#step-2';
Styles are computed from what is declared, not from a stylesheet. getComputedStyle in jsdom resolves inline styles and stylesheet rules it has been given, but a import './Button.css' never reaches it โ which is exactly why the standard config stubs CSS imports with a module mapper instead of trying to parse them.
// jest.config.js โ stop the CSS import from crashing the module graph
module.exports = {
moduleNameMapper: { '\\.(css|scss|less)$': 'identity-obj-proxy' },
};
The gaps that need a setup file are short and stable. matchMedia is not implemented, scrollIntoView is not implemented, ResizeObserver and IntersectionObserver are not implemented, and window.scrollTo is a no-op. Each is a handful of lines in setupFilesAfterEnv, and each is worth writing once centrally rather than per file.
// jest.setup.ts โ the four gaps a component suite usually hits
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: (query: string) => ({
matches: false, media: query, onchange: null,
addListener: jest.fn(), removeListener: jest.fn(),
addEventListener: jest.fn(), removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}),
});
Element.prototype.scrollIntoView = jest.fn(); // not implemented at all
global.ResizeObserver = jest.fn(() => ({ // constructor only
observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(),
}));
global.IntersectionObserver = global.ResizeObserver; // same shape
Because the environment is created per file, the document a test file receives has already been reused by every test in that file. document.body accumulates whatever previous tests rendered, so a cleanup step is not optional โ it is what keeps screen.getByRole from finding the previous test’s markup. React Testing Library’s automatic cleanup handles it when the setup file is loaded; a suite without the library has to do it by hand.
// cypress-free manual cleanup: the DOM is shared across tests in the file
afterEach(() => {
document.body.innerHTML = ''; // or: cleanup() from @testing-library/react
localStorage.clear(); // storage is shared too
});
c. happy-dom โ the faster environment and its trade-offs
happy-dom is a DOM implementation written for speed, and it plugs into Jest through a separate environment package. The install is two commands and the config change is one key, which is why it gets adopted for suites where jsdom construction dominates the run.
npm i -D happy-dom @happy-dom/jest-environment
// jest.config.js โ swap the environment for the whole run
module.exports = {
testEnvironment: '@happy-dom/jest-environment',
testEnvironmentOptions: { url: 'http://localhost/' },
};
The per-file form works the same way as with jsdom, using the environment’s package name in the pragma. This is the useful shape for an incremental migration: leave the suite on jsdom, move the fast, DOM-light files one at a time, and compare a failing result against jsdom before deciding it is a component bug.
/**
* @jest-environment @happy-dom/jest-environment
*/
test('renders without a full jsdom', () => {
document.body.innerHTML = '<button>Save</button>';
expect(document.querySelector('button')?.textContent).toBe('Save');
});
What it buys is startup. Constructing a JSDOM is the dominant fixed cost of a DOM test file, and happy-dom has invested specifically in making that construction cheap โ its own documentation makes the perf claim, and the effect in a large suite is visible as a shorter wall-clock run with the same test count. What it costs is fidelity at the edges: jsdom is the more mature and more spec-aligned of the two, its event and history behaviour track the standards closely, and a suite whose components depend on the exact ordering of a pointer sequence or the precise shape of a History entry is more likely to see a behavioural difference under happy-dom.
Neither environment has a layout engine. That is the important shared limitation: whichever one a suite picks, getBoundingClientRect() returns zeros, nothing is measured, and an assertion about size or position is an assertion about the environment rather than the application.
// true under both jsdom and happy-dom: no layout engine, no measurements
const { width, height } = document.body.getBoundingClientRect();
expect(width).toBe(0);
expect(height).toBe(0);
The pragmatic rule is to choose jsdom and change only when the numbers justify it. jsdom is bundled as Jest’s official environment, its behaviour is documented and its failures are widely reported, and a suite that hits an edge case will find an answer. happy-dom is the right pick when the suite is large, the components are straightforward, and the measured difference in run time is real โ and the way to establish that is to run both against the same suite and compare, not to adopt it on the strength of the claim.
d. The window.location spec change and the four workarounds
The change is a single line of Web IDL. In the HTML specification, the location attribute on Window is declared [LegacyUnforgeable] readonly attribute Location location, and that marker means the property is created on each window as an own property with configurable: false. A non-configurable property cannot be deleted and cannot be redefined.
// the snippet every suite used to carry โ now fails
delete window.location; // returns false, or throws in strict mode
window.location = { href: '/cart' } as any; // TypeError: Cannot set property
// the other common snippet โ fails for the same reason
Object.defineProperty(window, 'location', {
value: { href: '/cart' },
});
// TypeError: Cannot redefine property: location
The first workaround is history.pushState, and it is the right one for any test whose goal is “the application should see a different URL”. It changes the URL without navigating, it fires no popstate for the push itself, and it works identically under jsdom and happy-dom.
// change the URL the component reads, without replacing the binding
window.history.pushState({}, '', '/orders/42?tab=items');
expect(window.location.pathname).toBe('/orders/42');
expect(window.location.search).toBe('?tab=items');
The second is spying on the navigation methods. assign, replace, and reload are ordinary methods on the Location instance โ they are not part of the unforgeable binding โ so replacing one on the instance lets a test assert that a redirect was requested without performing it, which also suppresses the “Not implemented: navigation” console error.
// assert the request, do not perform the navigation
const replace = jest.spyOn(window.location, 'replace').mockImplementation(() => {});
document.querySelector<HTMLButtonElement>('[data-cy=pay]')!.click();
expect(replace).toHaveBeenCalledWith('/checkout/complete');
The third is the environment URL. When the URL is a fixed input rather than something the test changes, it belongs in testEnvironmentOptions.url or in the file’s @jest-environment-options pragma โ set once at construction, correct for every assertion in the file, no monkey-patching at all.
/**
* @jest-environment jsdom
* @jest-environment-options {"url": "https://shop.example.com/checkout?coupon=SAVE10"}
*/
test('reads the coupon from the URL', () => {
expect(new URLSearchParams(window.location.search).get('coupon')).toBe('SAVE10');
});
The fourth is to stop touching location in the test at all. A component that navigates through a router library โ next/navigation, react-router, Vue Router โ is calling a module, and the module is the thing to mock. A jest.mock of the router gives a stable object the test controls, and it decouples the test from a DOM binding that the specification deliberately made hostile.
// mock the module the component actually calls, not the DOM binding
jest.mock('next/navigation', () => ({
useRouter: () => ({ push: jest.fn(), replace: jest.fn() }),
usePathname: () => '/cart',
useSearchParams: () => new URLSearchParams('?coupon=SAVE10'),
}));
One consequence is worth noting: jest.spyOn(window.location, 'replace') installs the mock on the instance, and the instance is created per file. jest.restoreAllMocks() in an afterEach puts the real method back, and a suite that skips the restore leaves a later test in the same file with a stubbed navigation it never asked for.
Complete Example Session
// ============================================
// PART 1: THE PROJECT CONFIGURATION
// ============================================
// jest.config.js
module.exports = {
projects: [
{
displayName: 'unit',
testEnvironment: 'node', // no DOM, no cost
testMatch: ['<rootDir>/src/lib/**/*.test.ts'],
},
{
displayName: 'components',
testEnvironment: 'jsdom', // Jest 27+ must be explicit
testEnvironmentOptions: { url: 'http://localhost:3000/' },
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
testMatch: ['<rootDir>/src/components/**/*.test.tsx'],
moduleNameMapper: { '\\.(css|scss)$': 'identity-obj-proxy' },
},
],
};
// ============================================
// PART 2: THE PER-FILE OVERRIDE
// ============================================
/**
* @jest-environment jsdom
* @jest-environment-options {"url": "https://shop.example.com/cart"}
*/
// src/components/CartLink.test.tsx
import { render, screen } from '@testing-library/react';
import { CartLink } from './CartLink';
test('builds the link from the current origin', () => {
render(<CartLink />);
// the environment options set the URL at construction
expect(screen.getByRole('link')).toHaveAttribute(
'href',
'https://shop.example.com/cart'
);
});
// ============================================
// PART 3: CHANGING THE URL WITH PUSHSTATE
// ============================================
test('reads the page number from the query string', () => {
window.history.pushState({}, '', '/orders?page=2');
render(<CartLink />);
expect(screen.getByTestId('page')).toHaveTextContent('2');
});
// ============================================
// PART 4: ASSERTING A REDIRECT WITHOUT NAVIGATING
// ============================================
test('redirects to checkout after a successful payment', () => {
const replace = jest
.spyOn(window.location, 'replace')
.mockImplementation(() => {}); // no navigation, no console error
render(<CartLink />);
screen.getByRole('button', { name: 'Pay' }).click();
expect(replace).toHaveBeenCalledWith('/checkout/complete');
replace.mockRestore(); // put the real method back
});
// ============================================
// PART 5: THE RELOAD CASE
// ============================================
test('reloads after the session expires', () => {
const reload = jest
.spyOn(window.location, 'reload')
.mockImplementation(() => {}); // jsdom cannot reload
render(<CartLink />);
screen.getByRole('button', { name: 'Retry' }).click();
expect(reload).toHaveBeenCalledTimes(1);
});
// ============================================
// PART 6: THE SETUP FILE FOR THE GAPS
// ============================================
// jest.setup.ts
import '@testing-library/jest-dom';
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: (query: string) => ({
matches: false, media: query, onchange: null,
addListener: jest.fn(), removeListener: jest.fn(),
addEventListener: jest.fn(), removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
}),
});
Element.prototype.scrollIntoView = jest.fn(); // missing from jsdom entirely
global.ResizeObserver = jest.fn(() => ({
observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(),
}));
// ============================================
// PART 7: THE HAPPY-DOM PROJECT
// ============================================
// jest.config.js โ one project on the faster environment
// {
// displayName: 'fast',
// testEnvironment: '@happy-dom/jest-environment',
// testMatch: ['<rootDir>/src/presentational/**/*.test.tsx'],
// }
test('renders markup without jsdom', () => {
document.body.innerHTML = '<ul><li>One</li></ul>';
expect(document.querySelectorAll('li')).toHaveLength(1);
});
// ============================================
// PART 8: MOCKING THE ROUTER INSTEAD OF LOCATION
// ============================================
jest.mock('next/navigation', () => ({
useRouter: () => ({ push: jest.fn(), replace: jest.fn() }),
usePathname: () => '/orders',
useSearchParams: () => new URLSearchParams('?page=2'),
}));
// ============================================
// PART 9: THE ASSERTION THAT BELONGS IN A BROWSER
// ============================================
test('is tall enough to read', () => {
render(<CartLink />);
// getBoundingClientRect returns zeros under jsdom and happy-dom
expect(screen.getByRole('link').getBoundingClientRect().height).toBe(0);
// assert on the declared style instead, which both environments resolve
expect(screen.getByRole('link')).toHaveStyle({ display: 'inline-block' });
});
// ============================================
// PART 10: THE CLEANUP
// ============================================
afterEach(() => {
jest.restoreAllMocks(); // un-stub location.replace / reload
document.body.innerHTML = ''; // the document is shared within a file
localStorage.clear(); // storage is shared within a file too
});
The ten parts covered the two-project configuration, the per-file @jest-environment-options override, history.pushState as the URL setter, the replace spy as a redirect assertion, the reload case, the setup file for jsdom‘s gaps, a happy-dom project alongside it, the router mock that replaces location patching, the assertion that must not be written against jsdom, and the cleanup that keeps a shared document from leaking.
Quick Reference
The three environments
| Environment | Package | Globals |
|---|---|---|
node | jest-environment-node | process, Buffer, no DOM |
jsdom | jest-environment-jsdom | window, document, history, location |
happy-dom | @happy-dom/jest-environment | Same shape, faster construction |
Configuration keys
| Key | Scope | Purpose |
|---|---|---|
testEnvironment | Config | Default environment for the run |
testEnvironmentOptions | Config | Passed to the constructor (url, pretendToBeVisual) |
testURL | Removed in Jest 27 | Replaced by testEnvironmentOptions.url |
@jest-environment | File docblock | Overrides the config for one file |
@jest-environment-options | File docblock | Merges options for one file |
projects | Config | Several environments in one run |
What jsdom provides
| Feature | Status |
|---|---|
HTML parsing, querySelector | Implemented |
| Events, dispatch, bubbling | Implemented |
history.pushState, popstate | Implemented |
location.hash assignment | Implemented |
location.href navigation | Not implemented (console error) |
requestAnimationFrame | Implemented via pretendToBeVisual |
getComputedStyle | Declared styles only |
Layout, getBoundingClientRect | Always zeros |
matchMedia, ResizeObserver | Not implemented |
scrollIntoView | Not implemented |
window.scrollTo | No-op |
window.location workarounds
| Need | Approach |
|---|---|
| Set the URL | window.history.pushState({}, '', path) |
| Fixed URL for the file | @jest-environment-options {"url": "..."} |
| Assert a redirect | jest.spyOn(window.location, 'replace') |
| Assert a reload | jest.spyOn(window.location, 'reload') |
| Component navigates via router | jest.mock the router module |
| Replace the binding itself | Not possible โ configurable: false |
Best Practices
โ Do This:
// Set the environment explicitly after Jest 27
testEnvironment: 'jsdom' // โ
// Install the environment package from Jest 28 on
npm i -D jest-environment-jsdom // โ
// Annotate the few files that differ
/** @jest-environment jsdom */ // โ
// Put a fixed URL in the environment options
testEnvironmentOptions: { url: 'http://localhost:3000/' } // โ
// Change the URL with pushState
window.history.pushState({}, '', '/orders?page=2'); // โ
// Assert a redirect by spying on the method
jest.spyOn(window.location, 'replace').mockImplementation(() => {}); // โ
// Polyfill the gaps once, in setupFilesAfterEnv
Element.prototype.scrollIntoView = jest.fn(); // โ
// Mock the router module when the component uses one
jest.mock('next/navigation', () => ({ ... })); // โ
โ Don’t Do This:
// Leave the default and expect a document
testEnvironment: 'node'; render(<App />); // โ
// Use the option Jest 27 removed
testURL: 'http://localhost' // โ
// Delete the binding
delete window.location; // โ
// Redefine the binding
Object.defineProperty(window, 'location', { value: {} }); // โ
// Assign href and expect a navigation
window.location.href = '/checkout'; // โ
// Assert on layout
expect(el.getBoundingClientRect().width).toBeGreaterThan(0); // โ
// Rely on the document being clean between tests
test('b', () => screen.getByRole('button')); // โ no cleanup
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
document is not defined | Jest 27 default is node | Set testEnvironment: 'jsdom' |
| Environment not found | Jest 28+ moved the package | Install jest-environment-jsdom |
Cannot redefine property: location | [LegacyUnforgeable] binding | history.pushState |
delete window.location returns false | Non-configurable | Stop replacing it |
| Console error about navigation | location.href assignment | Spy on replace, or mock the router |
getBoundingClientRect all zeros | No layout engine | Assert on text or role |
matchMedia is not a function | Not implemented | Polyfill in setup |
scrollIntoView is not a function | Not implemented | Element.prototype.scrollIntoView = jest.fn() |
| Previous test’s markup found | Document shared within a file | document.body.innerHTML = '' |
testURL rejected | Removed in Jest 27 | testEnvironmentOptions.url |
Real-World Examples
1. Global default
module.exports = { testEnvironment: 'jsdom' };
2. Per-file override
/** @jest-environment jsdom */
3. Per-file URL
/** @jest-environment jsdom
* @jest-environment-options {"url": "https://shop.example.com/cart"} */
4. Global URL
testEnvironmentOptions: { url: 'http://localhost:3000/' }
5. Change the URL
window.history.pushState({}, '', '/orders?page=2');
6. Assert a redirect
const r = jest.spyOn(window.location, 'replace').mockImplementation(() => {});
expect(r).toHaveBeenCalledWith('/done');
7. Assert a reload
jest.spyOn(window.location, 'reload').mockImplementation(() => {});
8. Match media
Object.defineProperty(window, 'matchMedia', { writable: true, value: stub });
9. Happy DOM
module.exports = { testEnvironment: '@happy-dom/jest-environment' };
10. Mock the router
jest.mock('next/navigation', () => ({ useRouter: () => router }));
Visual
The environment layer
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ THE ENVIRONMENT LAYER โ
โ โ
โ jest worker process โ
โ โโ testEnvironment โ
โ โโ node โ process, Buffer, no document โ
โ โโ jsdom โ window, document, history โ
โ โ
โ one instance per test file โ
โ globalThis of the file = that instance's global โ
โ torn down when the file finishes โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
What jsdom implements
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WHAT JSDOM IMPLEMENTS โ
โ โ
โ yes HTML parsing, querySelector, createElement โ
โ yes events, bubbling, dispatchEvent โ
โ yes history.pushState, popstate, location.search โ
โ yes location.hash assignment โ
โ yes requestAnimationFrame (pretendToBeVisual) โ
โ โ
โ no layout โ getBoundingClientRect returns zeros โ
โ no painting โ nothing is ever off-screen โ
โ no location.href navigation โ console error โ
โ no matchMedia, ResizeObserver, scrollIntoView โ
โ no stylesheets โ CSS imports are stubbed โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The unforgeable binding
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ WINDOW.LOCATION IS UNFORGEABLE โ
โ โ
โ window โ
โ โโ location โ own, configurable: false โ
โ โโ assign() ordinary method, spyable โ
โ โโ replace() ordinary method, spyable โ
โ โโ reload() ordinary method, spyable โ
โ โ
โ delete window.location โ false / TypeError โ
โ Object.defineProperty(window, โ TypeError: โ
โ 'location', { value }) Cannot redefine โ
โ โ
โ history.pushState({}, '', url) โ changes the URL โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Choosing an environment
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CHOOSING AN ENVIRONMENT โ
โ โ
โ needs document / window? โ
โ โโ no โโโบ node fastest, plain globals โ
โ โโ yes โโโบ needs layout? โ
โ โโ yes โโโบ neither โ use a real browser โ
โ โโ no โโโบ does the suite hit jsdom โ
โ edge cases? โ
โ โโ yes โโโบ jsdom โ
โ โโ no โโโบ happy-dom โ
โ if measured โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Jest 27 default | testEnvironment: 'node' |
| Jest 26 default | testEnvironment: 'jsdom' |
| Jest 28 change | Environments moved to separate packages |
testURL | Removed in Jest 27, use testEnvironmentOptions.url |
| Per-file override | @jest-environment docblock |
| Per-file options | @jest-environment-options docblock |
jsdom layout | None โ rectangles are zeros |
jsdom navigation | Not implemented except hash changes |
happy-dom package | @happy-dom/jest-environment |
window.location binding | Own, configurable: false |
| URL setter that works | history.pushState |
| Redirect assertion | Spy on location.replace |
Key takeaways:
- The environment is a per-file object, not a global setting. Jest constructs one instance per test file, installs its globals on that file’s
globalThis, and destroys it when the file ends. Nothing carries between files, everything carries between tests inside a file, which is why cleanup belongs inafterEach. - Jest 27 changed the default to
nodeand Jest 28 moved the packages out. A suite upgrading across either boundary fails withdocument is not definedortestEnvironment jsdom is not resolvable, and both fixes are configuration rather than code โ settestEnvironmentexplicitly and installjest-environment-jsdom. testURLis gone. It was removed in Jest 27 in favour oftestEnvironmentOptions.url, and the per-file form is the@jest-environment-optionspragma. A fixed URL set at construction is correct for every assertion in a file that does not navigate.jsdomhas no layout engine.getBoundingClientRect()returns zeros,offsetWidthis zero,scrollIntoViewdoes not exist, andmatchMediadoes not exist. Any assertion about size, position, or whether an element is on screen is an assertion about the environment; the fix is to assert on role, text, attribute, or declared style, and move the geometry check into a real browser.window.locationcannot be replaced. The HTML specification marks the binding[LegacyUnforgeable], which makes it an own non-configurable property ofwindow. Thedelete window.locationidiom is dead and there is no monkey-patch that revives it.- There are four things to do instead.
history.pushStateto change the URL,testEnvironmentOptions.urlto fix it, a spy onlocation.assign/replace/reloadto assert a navigation request, and ajest.mockof the router module when the component navigates through a library. The last one is the most robust, because it removes the test’s dependence on the DOM binding entirely. happy-domis a speed decision, not a fidelity decision. It constructs faster, which matters once a suite has hundreds of files, and it has the same layout gap. Adopt it when a measured comparison shows a real gain on the suite in question, and keepjsdomfor the files that depend on precise event or history behaviour.
Remember: The environment key decides what a test file can see, and the two failures to keep straight are the ones that look alike and have nothing in common. document is not defined is a configuration problem โ the file is running in the node environment, either because the suite never set the key after the Jest 27 default flip or because the docblock is missing on the one file that renders. Cannot redefine property: location is a specification problem โ the binding is unforgeable, and no amount of patching restores the old idiom. Solve the first by setting testEnvironment and installing the package; solve the second by never replacing the binding, changing the URL through history.pushState, and asserting a navigation with a spy on the method or a mock of the router. Everything else the environment offers sits on top of those two, and neither is a browser.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!