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:
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 as
Unforgeable
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); });
To keep it short, "global" is "window" in Jest.
Use:
global.location.assign(url);
I believe that you can find the rest of the answer in How can I mock the JavaScript window object using Jest?.
Also, there is an interesting conversation around this on this issue:
I found window is global in Jest from Stack Overflow, but not mentioned in documentation #3692
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With