reactjs - 如何模拟 window.screen.width 属性?
问题描述
我的组件中有这种情况。
{window.screen.width > 1000 && (
<WebFeatures
scrolling={this.handleScrollToStats}
ref_var={this.statsRef}
ref_app={this.myRef}
ref_reimburse={this.reimburse}
ref_expense={this.expense}
/>``
)}
我该如何测试这种情况?
解决方案
您可以使用spyOn
onwindow.secreen.width
并返回测试所需的值:
jest.spyOn(window.screen, "width", "get").mockReturnValue(WIDTH);
您的测试将如下所示:
it("Should NOT render WebFeatures in small screen", () => {
jest.spyOn(window.screen, "width", "get").mockReturnValue(1000);
const wrapper = mount(<YourComponent />);
expect(wrapper.find("WebFeatures").exists()).toBe(false);
});
it("Should render WebFeatures in large screen", () => {
jest.spyOn(window.screen, "width", "get").mockReturnValue(1001);
const wrapper = mount(<YourComponent />);
expect(wrapper.find("WebFeatures").exists()).toBe(true);
});
推荐阅读
- powershell - 如何使用 PowerShell 获取 Active Directory 中子 OU 中的所有计算机?
- python - 运行 PyTorch 脚本时“预期很长但得到了 Int”
- python - 如何在 python 中并行化 csv 合并算法?
- excel - 如何在列中查找值并将范围从其他工作表粘贴到其相邻列中
- c - 如何在我的流程中模拟或注入错误
- java - Apache POI 错误的单元格字体设置
- html - Wordpress如何去除文章元素白色背景
- gis - 谁能指导我参考生成中性景观模型的 Netlogo 代码示例?
- c++ - 如何在不使用数学的情况下知道一个数字是否是回文?
- ejabberd - 是否有任何 API 可以更改用户的用户名