Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest error when set or assign window.location

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 as Unforgeable

To fix failing tests I used:

  1. window.history.pushState({}, "title", "/testJest");

  2. 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); });

like image 798
Mihai B. Avatar asked Oct 15 '22 06:10

Mihai B.


1 Answers

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

like image 60
Yalung Tang Avatar answered Nov 02 '22 08:11

Yalung Tang