首页 > 解决方案 > 如何模拟 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}
            />``
          )}

我该如何测试这种情况?

标签: reactjsjestjsenzyme

解决方案


您可以使用spyOnonwindow.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);
});


推荐阅读