Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

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

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.

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.

question from:https://stackoverflow.com/questions/45868042/figuring-out-how-to-mock-the-window-size-changing-for-a-react-component-test

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...