I am trying to run a test on a component at a certain viewport width. I am doing the following, but this doesn't seem to change it:
test('Component should do something at a certain viewport width.', () => { global.innerWidth = 2000; const component = mount(<SomeComponent />); ... });
I also found an article that explains how to do it using JSDom, but as Jest now ships with JSDom, I wondered if there was a native solution.
https://www.codementor.io/pkodmad/dom-testing-react-application-jest-k4ll4f8sd
Both Jest and Enzyme are meant to test the react applications. Jest can be used with any other Javascript framework, but Enzyme is meant to run on react only. Jest can be used without Enzyme, and snapshots can be created and tested perfectly fine. But the Enzyme adds additional functionality to it.
Testing the Next.In the project root directory, create a new folder called tests , which will be used by Jest to look up tests. Then, create a new file called index. test. js .
Background Information:
jsdom
does not implement window.resizeBy()
or window.resizeTo()
jsdom
defines the window innerWidth and innerHeight to be 1024 x 768jsdom
by manually setting window.innerWidth and window.innerHeight and firing the resize
eventHere 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>'); }); });
Notes:
Enzyme
v3 shallow
calls React lifecycle methods like componentDidMount()
so it can be used in place of mount
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With