Search code examples
reactjsunit-testingsnapshotreact-testing-library

Mock state in react snapshot test?


Hil,

I would like to complete the following snapshot test but I don't know how to pass in state which is required for the page to render.

test('test renders as per snapshot', () => {
        const state = {
            orderNumber: 1000000001,
            userID: 1234567,
          }
        const tree = renderer
            .create(<Order location={ state }></Order>)
            .toJSON();
        expect(tree).toMatchSnapshot();
    });

I get this error

 TypeError: Cannot read property 'orderNumber' of undefined
> 40 |       this.props.location.state.orderNumber;

Can someone please tell me how I can pass this to my snapshot test so it doesnt fail?


Solution

  • You should pass in the component as <Order location={{ state }}></Order> (notice the additional curly braces), as it's equal to <Order location={{ state: state }}></Order>

    In your post, <Order location={ state }> means to pass in state as a variable as 'props', and this.props.location.state would be undefined, thus led to your error.