Mock window.location in unit tests

When you run unit tests (I am using Jestjs) on functions which read window.location.href or, you need to somehow mock the value.

Problem is that when you try to edit the value of it will not work. Neither will work overriding it by Object.defineProperty(). But there is a simple workaround solution, and that is using history.pushState(). By that you can change the current URL to whatever value you need, and then read it by tested function.


beforeEach(() => {
 const search = `a=aaaa&b=bbb`;
 window.history.pushState({}, 'Test Page Title', `/any/url/you/like?${search}`);

Coding drunk make programming fun again book |
Well… I just liked the image 🙂