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

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

    Based on examples above and in other threads, here is a concrete example using jest that might help someone:

    describe('Location tests', () => {
        const originalLocation = window.location;
    
        const mockWindowLocation = (newLocation) => {
            delete window.location;
            window.location = newLocation;
        };
    
        const setLocation = (path) =>
            mockWindowLocation(
                new URL(`https://example.com${path}`)
            );
    
        afterEach(() => {
            // Restore window.location to not destroy other tests
            mockWindowLocation(originalLocation);
        });
    
        it('should mock window.location successfully', () => {
            setLocation('/private-path');
    
            expect(window.location.href).toEqual(
                `https://example.com/private-path`
            );
        });
    });
    

提交回复
热议问题