Tag Archives: Vue

Vue testing with Jest: Mock window.location

The bottom line is that you can not mock window.location, BUT you can delete it and create your own to use in test. I will here show one example of how this can be achived:

describe('methodUnderTest', () => {
  // Save current windows.location
  const oldWindowLocation = window.location;
  // Some mocked value
  const mockedUrl = 'https://blog.niklasottosson.com';

  beforeEach(() => {
    // Remove windows.location so that we can create a new
    delete window.location;

    // Create a new mutable window.location
    window.location = Object.defineProperties(
      {},
       {   // copy all properties from the old window.location
        ...Object.getOwnPropertyDescriptors(oldWindowLocation),
        // Start mocking...
        assign: {
           configurable: true,
           value: jest.fn()
        },
        href: {
            configurable: true,
            value: mockedUrl
        }
     );
  });

  afterEach(() => {
    // Restore window.location
    window.location = oldWindowLocation;
  });

  // Start creating your tests...
  it('should...', () => {
    ...
  } 

Tested on OSX 10.15.7, Vue v2.6.12 and Jest v26.0.14