Skip to content

Instantly share code, notes, and snippets.

@vinnymac
Created February 1, 2023 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vinnymac/5330aaf0a33512c6829cae91c8eb0557 to your computer and use it in GitHub Desktop.
Save vinnymac/5330aaf0a33512c6829cae91c8eb0557 to your computer and use it in GitHub Desktop.
Jest 26 Mock Window Location
// Jest 26 with latest JSDOM prevents location from being proxied
// Instead we can redefine location on window, and then restore.
export function mockWindowLocation(
mockLocation: Partial<Location> = {
href: '',
assign: jest.fn(),
reload: jest.fn(),
}
) {
const savedLocation = window.location;
beforeEach(() => {
Object.defineProperty(window, 'location', {
writable: true,
value: mockLocation,
});
});
afterEach(() => {
window.location = savedLocation;
});
return (mockLocation: Partial<Location>) => {
Object.defineProperty(window, 'location', {
writable: true,
value: mockLocation,
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment