弄清楚如何模拟改变反应组件测试的窗口大小 [英] Figuring out how to mock the window size changing for a react component test

查看:192
本文介绍了弄清楚如何模拟改变反应组件测试的窗口大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上当组件安装时,我有一个事件监听器监听resize事件。它切换isMobileView状态,然后将其作为道具传递给子项。因此,这是必要的,这是有效的,并经过测试。我是一个相当新的测试人员,我正试图找出一种方法,我可以编写一个测试来调整窗口大小并使所有逻辑发生并测试它是如何执行的。

So basically when the component mounts, I have an event listener listen for resize events. It toggles the isMobileView state and then passes it into the children as a prop. So it's imperative that this works and is tested. I'm fairly new to testing and I'm trying to figure out a way I can write a test that resizes the window and makes all the logic happen and test that it executed how it should.

这是代码 -

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

我知道代码有效,但我想为它编写一个测试。基本上只是确保状态正确变化的东西。

I know the code works, but I want to write a test for it. Basically just something that makes sure the state changes correctly.

推荐答案

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

Using Jest and Enzyme you can do the following. Jest has JSDOM baked in. In your tests Jest provides the window object and it is represented by global (I think that the default window.innerWidth set by Jest is 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.
});

这篇关于弄清楚如何模拟改变反应组件测试的窗口大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆