问题
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 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); });
回答1:
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 here:
How to mock the JavaScript window object using Jest?
Also, there is an interesting conversation around this on this issue:
https://github.com/facebook/jest/issues/3692
Hope this solves your problem.
来源:https://stackoverflow.com/questions/59954101/jest-error-when-set-or-assign-window-location