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

后端 未结 13 770
轻奢々
轻奢々 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 01:07

    2020 Update


    Basic

    The URL object has a lot of the same functionality as the Location object. In other words, it includes properties such as pathname, search, hostname, etc. So for most cases, you can do the following:

    delete window.location
    window.location = new URL('https://www.example.com')
    

    Advanced

    You can also mock Location methods that you might need, which don't exist on the URL interface:

    const location = new URL('https://www.example.com')
    location.assign = jest.fn()
    location.replace = jest.fn()
    location.reload = jest.fn()
    
    delete window.location
    window.location = location
    

提交回复
热议问题