I upgraded the Jest library to v25 and all unit tests that were checking location change are failing.
I checked a couple of issues opened on the Jest repository, but I didn't actually understand how can this be fixed.
The code that calls location.assign breaks with the following error:
Error: Not implemented: navigation (except hash changes)
69 | // window.location.href = url;
> 70 | window.location.assign(url);
I suppose that the Jest jsdom window object shouldn't be treated any more like a real browser window with regards to changing the location.
How can I fix this?
My findings:
- Navigation in the tests doesn't work. All these methods that work in the 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); });