Skip to content

Instantly share code, notes, and snippets.

@publicJorn
Created March 28, 2022 10:15
Show Gist options
  • Save publicJorn/ff81a33957ae13ffb211988bfae4cc58 to your computer and use it in GitHub Desktop.
Save publicJorn/ff81a33957ae13ffb211988bfae4cc58 to your computer and use it in GitHub Desktop.
Snippet to test different window sizes in jest
window.resizeTo = function resizeTo(width:number, height: number) {
Object.assign(this, {
innerWidth: width,
innerHeight: height,
outerWidth: width,
outerHeight: height,
}).dispatchEvent(new this.Event('resize'))
}
@publicJorn
Copy link
Author

publicJorn commented Mar 28, 2022

Found here: https://spectrum.chat/testing-library/help-react/how-to-set-window-innerwidth-to-test-mobile~70aa9572-b7cc-4397-92f5-a09d75ed24b8

I have this setup like so:

jest.config.js

module.exports = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
  // ...and other stuff
}

jest.setup.js

window.resizeTo = function resizeTo(width:number, height: number) {
  Object.assign(this, {
    innerWidth: width,
    innerHeight: height,
    outerWidth: width,
    outerHeight: height,
  }).dispatchEvent(new this.Event('resize'))
}

// ...and other stuf

MyComponent.test.tsx

test('My responsive test', () => {
  window.resizeTo(400, 600)
  // ... and start testing
})

You can also simply put it in the beforeEach function, but it's likely you'll need it more often.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment