首页 > 解决方案 > 如何使用 Jest 测试不同的屏幕宽度

问题描述

有人知道如何使用 Jest 测试 React 组件的不同屏幕宽度或响应能力吗?我一直在寻找一种正确的方法来做到这一点,但没有一个解决方案对我有用。例如,我发现有人建议matchMediaPolyfill(window)和有人建议用自定义宽度模拟一个 div,但这些解决方案都没有奏效。请帮忙!谢谢!

标签: javascriptreactjsunit-testingjestjsresponsive

解决方案


Jest用于jsdom模拟浏览器。

jsdom 将窗口宽度和高度定义为 1024 x 768

您可以手动设置window宽度和高度并resize根据需要触发事件。

这是一个例子:


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

推荐阅读