vue.jsunit-testingjestjsjasminevue-test-utils

How to mock window.location.href with Jest + Vuejs?


Currently, I am implementing unit tests for my project and there is a file that contains window.location.href.

I want to mock this to test and here is my sample code:

it("method A should work correctly", () => {
      const url = "http://dummy.com";
      Object.defineProperty(window.location, "href", {
        value: url,
        writable: true
      });
      const data = {
        id: "123",
        name: null
      };
      window.location.href = url;
      wrapper.vm.methodA(data);
      expect(window.location.href).toEqual(url);
    });

But I get this error:

TypeError: Cannot redefine property: href
        at Function.defineProperty (<anonymous>)

How should I resolve it?


Solution

  • You can try:

    window = Object.create(window);
    const url = "http://dummy.com";
    Object.defineProperty(window, 'location', {
      value: {
        href: url
      },
      writable: true // possibility to override
    });
    expect(window.location.href).toEqual(url);  
    

    Have a look at the Jest Issue for that problem:
    Jest Issue