Jest error when set or assign window.location

扶醉桌前 提交于 2021-02-18 12:38:08

问题


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:

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


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!