How to change the URL in your Jest unit-tests

It has been a pain to mock window.location in a robust way through the different versions of Jest.

Just push a new state!

If you only need to test a feature based on the location href/search, the simplest way might be to push a new state via the window history before your test:

window.history.pushState({}, '', new URL('http://localhost/new-page/'))

Then you can check, for instance:

expect(window.location.href).toBe('http://localhost/new-page/')

Limitations

Using a URL not belonging to the same domain would throw a security error. In some older versions of Jest, you could tweak testURL and use any domain you’d like, but using localhost should work just fine!