jestjs – Jest / Enzyme – 如何在不同的视口进行测试?

前端之家收集整理的这篇文章主要介绍了jestjs – Jest / Enzyme – 如何在不同的视口进行测试?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在某个视口宽度的组件上运行测试.我正在做以下事情,但这似乎没有改变它:
test('Component should do something at a certain viewport width.',() => {
    global.innerWidth = 2000;
    const component = mount(<SomeComponent />);
    ...
});

我还发现了一篇文章,解释了如何使用JSDom来实现它,但是当Jest现在随JSDom提供时,我想知道是否有原生解决方案.

https://www.codementor.io/pkodmad/dom-testing-react-application-jest-k4ll4f8sd

解决方法

背景资料:

> jsdom does not implement window.resizeBy()或window.resizeTo()
> jsdom defines the window innerWidth and innerHeight为1024 x 768
>通过手动设置window.innerWidth和window.innerHeight并触发resize事件,可以使用jsdom模拟窗口调整大小

这是一个例子:

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

笔记:

>从酶v3浅calls React lifecycle methods like componentDidMount()开始,因此它可以用来代替安装
>这个答案大量借鉴了here,here,here和@ JoeTidee自己的答案here.

原文链接:https://www.f2er.com/html5/168270.html

猜你在找的HTML5相关文章