Links:
Last active
May 23, 2024 20:32
-
-
Save remarkablemark/5cb571a13a6635ab89cf2bb47dc004a3 to your computer and use it in GitHub Desktop.
How to mock `window.location.reload` in Jest and jsdom: https://remarkablemark.org/blog/2018/11/17/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
it('mocks window.location.reload', () => { | |
const { location } = window; | |
delete window.location; | |
window.location = { reload: jest.fn() }; | |
expect(window.location.reload).not.toHaveBeenCalled(); | |
window.location.reload(); | |
expect(window.location.reload).toHaveBeenCalled(); | |
window.location = 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
{ | |
"scripts": { | |
"test": "jest" | |
}, | |
"dependencies": { | |
"jest": "latest" | |
} | |
} |
With TypeScript, the above gave me
Type '{ reload: Mock<any, any>; }' is missing the following properties from type 'Location': ancestorOrigins, hash, host, hostname, and 8 more.
This worked for me:delete window.location window.location = { ...window.location, reload: jest.fn() }With this I get the error:
The operand of a 'delete' operator must be optional.
Any ideas on how to fix? I've disabled TS for that line for now for as a temp fix.@inalbant, you can use a type assertion:
// Type assertion is used so TypeScript won't complain about // deleting the required property, `window.location`. delete (window as Partial<Window>).location; window.location = { ...window.location, reload: jest.fn() };
Solved my issue, thank you so much 🙏
@laurenbarker You saved my life 🙏
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How is it this is working when the property is already deleted? (I'm using with TypeScript.)