Created
February 1, 2023 03:22
-
-
Save vinnymac/5330aaf0a33512c6829cae91c8eb0557 to your computer and use it in GitHub Desktop.
Jest 26 Mock Window Location
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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