Personal Blog

Mocking window object with jest

Wed 15 Apr 2020

In order to mock window we first need to retrieve it. It can be retrieved just by window. Save the property so you can put it back at the end of the suite or test.

// Save initial property
let { location }: any = window
beforeAll(() => {
    // Delete property so we can reassign it
    delete window.location;
})

it('inside the test', () => {
    // Mocking property
    window.location = { pathname: 'https://zan.sh/any/path' } as any;
})

afterAll(() => {
    // Put back the original property
    window.location = location;
})

Happy mocking 😉