Does anybody know how to test different screen widths or responsiveness of a React component using Jest? I have been searching for a proper way of doing this, but none of the solutions have been working for me. For instance, I found someone suggest matchMediaPolyfill(window)
and someone suggesting mocking a div with custom width but none of these solutions worked. Please help! Thank you!
Asked
Active
Viewed 1.0k times
8
1 Answers
8
Jest
uses jsdom
to simulate a browser.
jsdom
defines the window width and height to be 1024 x 768
You can manually set the window
width and height and fire the resize
event as needed.
Here is an example:
comp.js
import * as React from 'react';
export default class Comp extends React.Component {
constructor(...args) {
super(...args);
this.state = { width: 0, height: 0 }
}
updateDimensions = () => {
this.setState({ width: window.innerWidth, height: window.innerHeight });
}
componentDidMount() {
this.updateDimensions();
window.addEventListener("resize", this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
render() {
return <div>{this.state.width} x {this.state.height}</div>;
}
}
comp.test.js
import * as React from 'react';
import { shallow } from 'enzyme';
import Comp from './comp';
const resizeWindow = (x, y) => {
window.innerWidth = x;
window.innerHeight = y;
window.dispatchEvent(new Event('resize'));
}
describe('Comp', () => {
it('should display the window size', () => {
const component = shallow(<Comp />);
expect(component.html()).toEqual('<div>1024 x 768</div>');
resizeWindow(500, 300);
expect(component.html()).toEqual('<div>500 x 300</div>');
resizeWindow(2880, 1800);
expect(component.html()).toEqual('<div>2880 x 1800</div>');
});
});

Brian Adams
- 43,011
- 9
- 113
- 111
-
3window.innerWidth and window.innerHeight are readonly methods, use the window.resizeTo(width, height) method. https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth – Roskow Apr 28 '21 at 07:49
-
1using `window.resizeTo` cannot be possible in testing because there's a strict condition of using it: > It's not possible to resize a window or tab that wasn't created by window.open(). It's also not possible to resize when the window has multiple tabs. – Halil Kayer Apr 18 '22 at 05:22