Mock window.location in unit tests

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

Problem is that when you try to edit the value of window.location.search 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.

Example

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 | StareCat.com
Well… I just liked the image 🙂