Skip to content

evelynhathaway/jest-location-mock

Repository files navigation

Jest Location Mock icon

Jest Location Mock

Jest hooks for JSDOM location mock

npm version check status license: MIT

Description

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.

Features

  • πŸ†• New in v3.0.0: Compatibility with JSDOM's window.history implementation and react-router-dom (see limitations)
  • πŸ†• New in v3.0.0: Compatibility with JSDOM v21+'s unconfigurable / unforgeable window.location
  • πŸŽ›οΈ Mocks and controls window.location in JSDOM Jest tests
  • πŸ•΅οΈβ€β™€οΈ Includes Jest spies all of the methods on window.location and window.history
  • βš“ Supports using relative URLs so pathnames that work in the browser also work in JSDOM
  • πŸ”• Prevents console.error messages from JSDOM when changing window.location
  • 🀐 Does not affect Jest environments without window, or in other words, it doesn't cause errors on mixed JSDOM / Node.js projects

Installation

npm install --save-dev jest-location-mock

Usage

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.

Quick Start

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";

Other Setup Methods

With Create React App (Easy)

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";
Without a Setup File (Easy)

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"
    ]
};
With TypeScript Jest Files

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";
Changing the Starting Location

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.

Selectively Include the Mock in Certain Test Files

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/");
});
Customizing the Behavior (Advanced)

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();
});

Limitations

  • Side effects of updating the location are not implemented This project expects to be used in a context where side effects are either ignored or handled by the tested code or the router provided by the framework it runs on.
    • JSDOM has limitations with navigation, and if you need a more rigorous test environment for the code you're testing, consider a browser based test technology like Playwright, Cypress, or Puppeteer.
  • JSDOM has limitations with history traversal: Navigation, including 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)
  • Relies on 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 patch

License

Copyright Evelyn Hathaway, MIT License