gpt4 book ai didi

reactjs - 如何模拟 window.screen.width 属性?

转载 作者:行者123 更新时间:2023-12-02 19:35:11 25 4
gpt4 key购买 nike

我的组件中有这个条件。

{window.screen.width > 1000 && (
<WebFeatures
scrolling={this.handleScrollToStats}
ref_var={this.statsRef}
ref_app={this.myRef}
ref_reimburse={this.reimburse}
ref_expense={this.expense}
/>``
)}

我怎样才能测试这个条件?

最佳答案

您可以在 window.secreen.width 上使用 spyOn 并返回测试所需的值:

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

关于reactjs - 如何模拟 window.screen.width 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61158106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com