Does anybody know how to test different screen widths or responsiveness of a React ponent 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!
Does anybody know how to test different screen widths or responsiveness of a React ponent 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!
1 Answer
Reset to default 12Jest
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:
p.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 });
}
ponentDidMount() {
this.updateDimensions();
window.addEventListener("resize", this.updateDimensions);
}
ponentWillUnmount() {
window.removeEventListener("resize", this.updateDimensions);
}
render() {
return <div>{this.state.width} x {this.state.height}</div>;
}
}
p.test.js
import * as React from 'react';
import { shallow } from 'enzyme';
import Comp from './p';
const resizeWindow = (x, y) => {
window.innerWidth = x;
window.innerHeight = y;
window.dispatchEvent(new Event('resize'));
}
describe('Comp', () => {
it('should display the window size', () => {
const ponent = shallow(<Comp />);
expect(ponent.html()).toEqual('<div>1024 x 768</div>');
resizeWindow(500, 300);
expect(ponent.html()).toEqual('<div>500 x 300</div>');
resizeWindow(2880, 1800);
expect(ponent.html()).toEqual('<div>2880 x 1800</div>');
});
});