最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test different screen widths using Jest - Stack Overflow

programmeradmin5浏览0评论

Does anybody know how to test different screen widths or responsiveness of a React ponent 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!

Does anybody know how to test different screen widths or responsiveness of a React ponent 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!

Share Improve this question edited Aug 20, 2020 at 20:43 skyboyer 23.7k7 gold badges62 silver badges71 bronze badges asked Aug 20, 2020 at 17:35 Jpark9061Jpark9061 1,1104 gold badges16 silver badges36 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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:


p.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 });
  }
  ponentDidMount() {
    this.updateDimensions();
    window.addEventListener("resize", this.updateDimensions);
  }
  ponentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions);
  }
  render() {
    return <div>{this.state.width} x {this.state.height}</div>;
  }
}

p.test.js

import * as React from 'react';
import { shallow } from 'enzyme';

import Comp from './p';

const resizeWindow = (x, y) => {
  window.innerWidth = x;
  window.innerHeight = y;
  window.dispatchEvent(new Event('resize'));
}

describe('Comp', () => {
  it('should display the window size', () => {
    const ponent = shallow(<Comp />);
    
    expect(ponent.html()).toEqual('<div>1024 x 768</div>');

    resizeWindow(500, 300);
    expect(ponent.html()).toEqual('<div>500 x 300</div>');

    resizeWindow(2880, 1800);
    expect(ponent.html()).toEqual('<div>2880 x 1800</div>');
  });
});
发布评论

评论列表(0)

  1. 暂无评论