Javascript 弄清楚如何模拟反应组件测试的窗口大小变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45868042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:15:03  来源:igfitidea点击:

Figuring out how to mock the window size changing for a react component test

javascriptreactjsunit-testingjestjsenzyme

提问by joe

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.

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

Here is the code -

这是代码 -

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.

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

回答by JoeTidee

Using Jest and Enzyme you can do the following. Jest has JSDOM baked in. In your tests Jest provides the windowobject and it is represented by global(I think that the default window.innerWidthset by Jest is 1024px):

使用 Jest 和 Enzyme,您可以执行以下操作。Jest 内置了 JSDOM。在您的测试中,Jest 提供了window对象,它由global(我认为window.innerWidthJest的默认设置为 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.
});

回答by Lauren Madigan

If you are getting the typescript error message

如果您收到打字稿错误消息

Cannot assign to 'innerWidth' because it is a read-only property.

无法分配给“innerWidth”,因为它是只读属性。

Try:

尝试:

Object.defineProperty(window, 'innerWidth', {writable: true, configurable: true, value: 200})

回答by Lital Levy

Try this line:

试试这一行:

window = Object.assign(window, { innerWidth: 500 });