javascript - 如何测试一个使用 window.screen.width 开玩笑的函数
问题描述
我试图开玩笑地测试这个功能,但我无法覆盖、调整屏幕大小或创建虚拟 dom。
我正在节点上运行此测试。ps:我尝试使用jsdom但失败了。
函数.js
export const getScreenWidth = () => {
const screenWidth = window.screen.width;
if (screenWidth <= 425) return "mobile";
if (screenWidth <= 768) return "tablet";
if (screenWidth <= 1024) return "laptopSm";
if (screenWidth <= 1440) return "laptopLg";
if (screenWidth <= 2560) return "HD";
return screenWidth;
};
解决方案
我试图制作这个模拟并且它有效,但我真的不知道这是否是正确的方法。
const mockScreen = (size) => {
global.window = {};
global.window.screen = {};
global.window.screen.width = size;
};
所以最终的测试将是
describe("getScreenWidth()", () => {
it.only("returns a string representing the width of the screen", () => {
const mockScreen = (size) => {
global.window = {};
global.window.screen = {};
global.window.screen.width = size;
};
mockScreen(425);
expect(jsf.getScreenWidth()).toBe("mobile");
mockScreen(2560);
expect(jsf.getScreenWidth()).toBe("HD");
});
});
推荐阅读
- python - Django TypeError 'dict' 对象不可调用
- boolean - 在方案中返回真或假 (#t & #f)
- android - 条目中的显示/隐藏图标未显示
- java - 将本机库与 JNI 一起使用时 Java 代码挂起
- django - 定义你自己的 Meta 类选项
- javascript - 简单单选按钮和 JavaScript 测验的问题
- r - 在 R Shiny 中下载压缩的 PNG
- reactjs - 使用 weekNumberCalculation 函数显示 React FullCalendar
- ffmpeg - 如何将不同分辨率的视频组合成单个 HLS 视频?
- oracle11g - Oracle11g 的“无效字符”错误,可能由_抛出?