javascript - 如何使用 Jest 测试不同的屏幕宽度
问题描述
有人知道如何使用 Jest 测试 React 组件的不同屏幕宽度或响应能力吗?我一直在寻找一种正确的方法来做到这一点,但没有一个解决方案对我有用。例如,我发现有人建议matchMediaPolyfill(window)
和有人建议用自定义宽度模拟一个 div,但这些解决方案都没有奏效。请帮忙!谢谢!
解决方案
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>');
});
});
推荐阅读
- android - Activity.setTheme() 之后的 Activity.recreate() 导致活动泄漏
- unique - 根据第二列计算列中的不同值
- xcode - 目标的构建设置中没有“金属编译器”
- generics - Kotlin 中的协议实现可识别的推断类型
- xcode - 在某些设备上查看效果不佳
- coq - 当 Coq 扩展一个函数作为目标的一部分时,这意味着什么?
- couchdb - CouchDB 2.x 下 local_seq 的行为是什么?
- javascript - 两个给定时间戳Javascript剩余的时间百分比
- sql - SQL选择依赖于条件计数
- python-3.x - 第三次尝试时未出现授予的访问权限