Mocking window object with Jest
Oct 14, 2021
Another unit test and another mocking issue. The code to be tested is more less like this:
To test this component we need to mock:
window.location.pathname
Static mocking if we need only one value:
Dynamic pathname mocking if we need the value to be changed during the test:
window.open
window.location.replace
Testing
First testing the pathname check — new window should be opened when specific path is within window.location.pathname
:
And the replacement of location:
The code
All the code can be find in this article’s repository: https://github.com/marekrozmus/blog-mocking-window-object-with-jest
Check also my other posts about unit testing: