How to mock [removed].href with Jest + Vuejs?

后端 未结 13 732
轻奢々
轻奢々 2020-12-24 00:32

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

I want to mock this to test and here is m

13条回答
  •  半阙折子戏
    2020-12-24 00:53

    The best is probably to create a new URL instance, so that it parses your string like location.href does, and so it updates all the properties of location like .hash, .search, .protocol etc.

    it("method A should work correctly", () => {
      const url = "http://dummy.com/";
      Object.defineProperty(window, "location", {
        value: new URL(url)
      } );
    
      window.location.href = url;
      expect(window.location.href).toEqual(url);
    
      window.location.href += "#bar"
      expect(window.location.hash).toEqual("#bar");
    });
    

    https://repl.it/repls/VoluminousHauntingFunctions

提交回复
热议问题