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

后端 未结 13 739
轻奢々
轻奢々 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

    Many of the examples provided doesn't mock the properties of the original Location object.

    What I do is just replace Location object (window.location) by URL, because URL contains the same properties as Location object like "href", "search", "hash", "host".

    Setters and Getters also work exactly like the Location object.

    Example:

    const realLocation = window.location;
    
    describe('My test', () => {
    
        afterEach(() => {
            window.location = realLocation;
        });
    
        test('My test func', () => {
    
            // @ts-ignore
            delete window.location;
    
            // @ts-ignore
            window.location = new URL('http://google.com');
    
            console.log(window.location.href);
    
            // ...
        });
    });
    

提交回复
热议问题