Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test different screen widths using Jest

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!

like image 313
Jpark9061 Avatar asked Oct 26 '22 18:10

Jpark9061


1 Answers

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>');
  });
});
like image 59
Brian Adams Avatar answered Nov 15 '22 13:11

Brian Adams