开玩笑/酶-如何在不同视口进行测试? [英] Jest / Enzyme - How to test at different viewports?
本文介绍了开玩笑/酶-如何在不同视口进行测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在某个视口宽度上对组件进行测试。我正在执行以下操作,但这似乎并没有改变它:
I am trying to run a test on a component at a certain viewport width. I am doing the following, but this doesn't seem to change it:
test('Component should do something at a certain viewport width.', () => {
global.innerWidth = 2000;
const component = mount(<SomeComponent />);
...
});
我还发现了一篇文章,解释了如何使用JSm进行此操作,但由于Jest现在与JSm一起提供,我想知道是否有本机解决方案。
I also found an article that explains how to do it using JSDom, but as Jest now ships with JSDom, I wondered if there was a native solution.
https://www.codementor.io/pkodmad/dom-testing-react-application-jest-k4ll4f8sd
推荐答案
背景信息:
-
jsdom
没有实现window.resizeBy()
或window.resizeTo()
-
jsdom
定义窗口innerWidth和innerHeight 为1024 x 768 - 通过手动设置window.innerWidth和window.innerHeight并触发
resize
事件,可以使用jsdom
模拟窗口调整大小
jsdom
does not implementwindow.resizeBy()
orwindow.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 theresize
event
以下是示例:
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
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开始浅
调用React生命周期方法,例如componentDidMount()
,因此可以代替mount
- 此答案大量借鉴了此处,此处, ,以及@JoeTidee自己的答案此处。
- As of
Enzyme
v3shallow
calls React lifecycle methods likecomponentDidMount()
so it can be used in place ofmount
- This answer borrows heavily from the information here, here, here, and @JoeTidee's own answer here.
这篇关于开玩笑/酶-如何在不同视口进行测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文