Jest / Enzyme – How to test at different viewports?

Background Information:

  • jsdom does not implement window.resizeBy() or window.resizeTo()
  • jsdom defines the window innerWidth and innerHeight to be 1024 x 768
  • It is possible to simulate a window resize using jsdom by manually setting window.innerWidth and window.innerHeight and firing the resize event

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:

  • As of Enzyme v3 shallow calls React lifecycle methods like componentDidMount() so it can be used in place of mount
  • This answer borrows heavily from the information here, here, here, and @JoeTidee’s own answer here.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)