首页 > 解决方案 > 如何测试一个使用 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;
};

标签: javascriptjestjswindowwidthscreen

解决方案


我试图制作这个模拟并且它有效,但我真的不知道这是否是正确的方法。

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

推荐阅读