gpt4 book ai didi

javascript - 弄清楚如何模拟 react 组件测试的窗口大小变化

转载 作者:行者123 更新时间:2023-12-03 13:02:31 24 4
gpt4 key购买 nike

所以基本上当组件安装时,我有一个事件监听器监听调整大小事件。它切换 isMobileView 状态,然后将其作为 prop 传递给子级。因此,它必须有效并经过测试。我对测试相当陌生,我正在尝试找出一种方法来编写一个测试来调整窗口大小并使所有逻辑发生并测试它是否按照应有的方式执行。

这是代码 -

componentDidMount() {
this.setMobileViewState()
window.addEventListener('resize', this.setMobileViewState.bind(this));
}

setMobileViewState() {
if(document.documentElement.clientWidth <= this.props.mobileMenuShowWidth) {
this.setState({ isMobileView: true })
} else {
this.setState({ isMobileView: false })
}
}

我知道代码可以工作,但我想为其编写一个测试。基本上只是确保状态正确改变的东西。

最佳答案

使用 Jest 和 Enzyme,您可以执行以下操作。 Jest 内置了 JSDOM。在您的测试中,Jest 提供了 window 对象,它由 global 表示(我认为默认的 window.innerWidth Jest 设置为 1024px):

test('Test something when the viewport changes.', () => {

// Mount the component to test.
const component = mount(<ComponentToTest/>);

...

// Change the viewport to 500px.
global.innerWidth = 500;

// Trigger the window resize event.
global.dispatchEvent(new Event('resize'));

...

// Run your assertion.
});

关于javascript - 弄清楚如何模拟 react 组件测试的窗口大小变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45868042/

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