Jest / Enzyme - How to test at different viewports?

JoeTidee picture JoeTidee · Sep 14, 2017 · Viewed 17.5k times · Source

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

Answer

Brian Adams picture Brian Adams · Aug 24, 2018

Background Information:

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>');
  });
});

Notes: