
Product
Socket for Jira Is Now Available
Socket for Jira lets teams turn alerts into Jira tickets with manual creation, automated ticketing rules, and two-way sync.
jest-location-mock
Advanced tools
Ever gotten the following error when using window.location = newHref, window.location.assign(), .reload(), or .replace()?
Error: Not implemented: navigation (except hash changes)
Or tried to mock window.location and gotten an error like this?
TypeError: Cannot redefine property: location
This Jest plugin fixes this error and mocks out window.location so it behaves similar to how does in the browser.
window.history implementation and react-router-dom (see limitations)window.locationwindow.location in JSDOM Jest testswindow.location and window.historyconsole.error messages from JSDOM when changing window.locationwindow, or in other words, it doesn't cause errors on mixed JSDOM / Node.js projectsnpm install --save-dev jest-location-mock
To start using Jest Location Mock, importing the default export will add a beforeAll() and beforeEach() hook that
will mock window.location and watch window.history.
jest.config.js
export default {
// [other Jest config properties...]
setupFilesAfterEnv: [
"./config/jest-setup.js"
]
};
config/jest-setup.js
// Mock `window.location` with Jest spies
import "jest-location-mock";
Create React App (react-scripts) automatically includes setupFilesAfterEnv if it finds a setup tests file. Add the following to the file if it exists, or create a file. You do not need to modify a Jest config unless you've ejected from Create React App.
src/setupTests.js or src/setupTests.ts
// Mock `window.location` with Jest spies
import "jest-location-mock";
If you don't want to group the location mock with any other test setup logic, you can just include the package name directly in the array.
jest.config.js
export default {
// [other Jest config properties...]
setupFilesAfterEnv: [
"jest-location-mock"
]
};
Jest setup and config files can be in TypeScript, given that you are already using ts-jest.
jest.config.ts
import type {Config} from "jest";
const config: Config = {
// [other Jest config properties...]
setupFilesAfterEnv: [
"./config/jest-setup.ts"
]
};
export default config;
config/jest-setup.ts
// Mock `window.location` with Jest spies
import "jest-location-mock";
The starting location is http://localhost/ by default. If process.env.HOST is set before the beforeEach() that creates the mock (e.g. a real environment variable or the value is set by JavaScript roughly right before each test is run), this value is used instead.
However, the most straightforward solution to changing the starting location is to be verbose about the desired location either in your setup file:
config/jest-setup.js
// Mock `window.location` with Jest spies
import "jest-location-mock";
beforeEach(() => {
window.location.href = "https://example.com";
});
Or in your tests:
__tests__/starting-location-example.test.js
beforeEach(() => {
window.location.href = "https://example.com";
});
This is by no means required, especially if you do not need to test for behavior dependant on the starting location or the origin.
If you do not include the default import in the test environment setup file, you can apply the mock only in certain test suites by importing it at the top of each file that needs the mock.
__tests__/needs-location-mock-example.test.js
// Mock `window.location` with Jest spies
import "jest-location-mock";
// Example test that will pass once the mock is imported
test("should not error when pressed", () => {
jest.spyOn(console, "error");
window.location.href = "https://example.com/";
expect(console.error).not.toHaveBeenCalled();
expect(window.location.href).toBe("https://example.com/");
});
If the default behavior of creating a beforeAll() and beforeEach() Jest hook that mocks the window.location and
listens to methods on window.history doesn't work best for you, you may replace the default import with a custom
setup.
config/jest-setup.js
// Remove: `import "jest-location-mock";`
// You may import the functions that run inside the hook and craft your own logic
import {replaceHistory, replaceLocation, reset} from "jest-location-mock/lib/hooks";
// `beforeAll()` is used by default to setup the mock on the window
beforeAll(() => {
// This is where the most of magic happens, you probably want to keep this
replaceLocation();
// New in v3.0.0, proxy and spy on `window.history` to support use cases like browser router from react-router-dom
// - Remove to isolate the `window.location` mock from `window.history`
replaceHistory();
});
// `beforeEach()` is used by default for a clean slate for each test
beforeEach(() => {
reset();
});
window.history, isn't fully implemented in
JSDOM. This project aims to improve the behavior of the location API without breaking tests that rely on JSDOM's
history API. However, the project currently does not replace their implementation, so any outstanding limitation of
JSDOM's window.history still applies.
window.history.back(), forward(), and go() will not error, but they will not reflect any history traversal
in window.location (jsdom#1565)window._globalProxy from JSDOM: This property has been available for years, but should it disappear in
a new JSDOM version, this project will stop working. Unfortunately between JSDOM making window.location
unconfigurable and not being open to an API for mocking purposes (since it's made for spec compliance, not testing
niches), there may not be a good workaround if it's removed. If you cannot update your tested code, this project aims
to be more stable than a package patchCopyright Evelyn Hathaway, MIT License
FAQs
Jest hooks for JSDOM location mock
The npm package jest-location-mock receives a total of 218,125 weekly downloads. As such, jest-location-mock popularity was classified as popular.
We found that jest-location-mock demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Socket for Jira lets teams turn alerts into Jira tickets with manual creation, automated ticketing rules, and two-way sync.

Company News
Socket won two 2026 Reppy Awards from RepVue, ranking in the top 5% of all sales orgs. AE Alexandra Lister shares what it's like to grow a sales career here.

Security News
NIST will stop enriching most CVEs under a new risk-based model, narrowing the NVD's scope as vulnerability submissions continue to surge.