Figuring out how to mock the window size changing for a react component test Figuring out how to mock the window size changing for a react component test reactjs reactjs

Figuring out how to mock the window size changing for a react component test


Using Jest and Enzyme you can do the following. Jest has JSDOM baked in. In your tests Jest provides the window object and it is represented by global (I think that the default window.innerWidth set by Jest is 1024px):

test('Test something when the viewport changes.', () => {    // Mount the component to test.    const component = mount(<ComponentToTest/>);    ...    // Change the viewport to 500px.    global.innerWidth = 500;    // Trigger the window resize event.    global.dispatchEvent(new Event('resize'));    ...    // Run your assertion.});


If you are getting the typescript error message

Cannot assign to 'innerWidth' because it is a read-only property.

Try:

Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 200})


Try this line:

window = Object.assign(window, { innerWidth: 500 });