Mocking window object with Jest

Marek Rozmus
Oct 14, 2021


Photo by Michael Jasmund on Unsplash

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:


Static mocking if we need only one value:

Dynamic pathname mocking if we need the value to be changed during the test:



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:

Check also my other posts about unit testing: