'Jest error when set or assign window.location
Upgraded Jest library on v25 and all unit tests that were checking location change are failing.
I checked a couple of issues opened on jest repo but I didn't actually understood how can this be fixed.
The code that calls location.assign breaks with following error:
Error: Not implemented: navigation (except hash changes)
69 | // window.location.href = url;
> 70 | window.location.assign(url);
I suppose that Jest jsdom window object shouldn't be treated anymore like a real browser window in regards to changing the location.
Any suggestion?
I will add my findings here:
- Navigation in the tests doesn't work. All these methods that work in browser are not implemented in the JSDom window:
window.location.href = "https://myapp.com"window.location.assign("https://myapp.com")window.location.replace("https://myapp.com")Object.defineProperty(window.location, "href", { writable: true, value: currentUrl }); window.location has been set asUnforgeable
To fix failing tests I used:
window.history.pushState({}, "title", "/testJest");delete window.location; window.location = { assign: jest.fn() };it("should navigate to the new URL", () => { const myUrl = "http://some.url"; expect(window.location.assign).toHaveBeenCalledWith(myUrl); });
Solution 1:[1]
Just add the following code in your test file.
Object.defineProperty(window, 'location', {
writable: true,
value: { assign: jest.fn() }
});
Solution 2:[2]
Following worked for me:
window.history.replaceState({}, "", decodeURIComponent(url));
happy coding :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sushil Kumar |
| Solution 2 | Luckylooke |
