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

Related searches

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.

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

Simulate window resize event in jsdom � GitHub, Figuring out how to mock the window size changing for a react component test. Question. So basically when the component mounts, I have an event listener� Figuring out how to mock the window size changing for a react component test - IT1352. 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 thi. IT1352.

If you are getting the typescript error message

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

Try:

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

testing-library/react-testing-library, 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 � Well, fortunately, if you know React you don’t have to worry. In the React world everything is simple, and this case is no different. What we have to do is just force re-render to our component each time the browser windows change size.

Try this line:

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

How to Fake the Window Object in Jest and Enzyme, Simulate window resize event in jsdom. Raw. test.js From my understanding, JSDom does not draw anything so it doesn't support viewport size changes. Some of these behaviors may be achievable with CSS, or by managing window size with the onResize event, but in the interest of building React components that are maximally reusable, it makes sense to encapsulate this logic into the component itself. That way, regardless of where/how the component is used, it will function correctly.

react-testing-library version: latest react version: 16.9.0 node version: n/a npm (or yarn) version: n/a Relevant innerHeight = 500 fireEvent(window, new Event(' resize')) What you did: ran t We'll have to figure out why this is requiring act . toBe(768) act(() => { // Change the viewport to 500px. window. @badsyntax As far as i have understand you cannot test your component in this way. The reason is, that - as you have already recognized - you have already decorated your class at import time and mocking the decorator at this point in time won't change your class's behaviour. Your only change is to use a factory function

Most of the solutions I found were people trying to mock window I will be using React components in this blog post, but there is no The problem comes when we try to write a unit test (in my case, using Jest and Enzyme) for this component. title expect(enzymeWrapper.find(".our-component").text()). the window object will still be available to you from your react component.. but the issue is that your defining your function just fine, but you're not calling it anywhere (is that jsonp syntax in the url of that script?). if you want that function to execute when you mount your component, you can make use of the component lifecycle hooks, specifically, componentDidMount

If you are using ES6 classes you can also go for the withRouter Hoc provided by react-router as mentioned here. This higher order component exposes a prop in your component called router. Using this prop you can redirect using this.props.router.push(<url>).

Comments
  • I can show you how to test this in mocha/sinon if that's worth anything to you.
  • @BenHare that would be perfect, I want an introduction to sinon so this would be a great time for me to learn it i guess. If I see working code it'll help me a lot though. Not sure if I can figure it out from other examples
  • Apologies I thought I could get it to work but I can't figure out how to stub document.documentElement
  • according to docs at developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth, innerWidth is read only. should we use window.resizeBy(x, y); instead?
  • I'm on Jest 23.6.0 and it works for me, maybe needs an upgrade 🤷‍♂️
  • Confirmed working still in Jest 24.1.0 as well. the resizeBy would make sense to use but Jest does not implement that and the innerWidth is not read only
  • It seems this no longer works: Property 'innerWidth' does not exist on type 'Global'
  • Working fine in Jest 21.2.1