Search code examples
javascriptreactjsjestjsenzyme

How to resolve "Invariant Violation" error, related to redux store?


I was trying to do DOM testing, to check whether a dialog box is opening on button click. Then I got this error

Invariant Violation: Could not find "store" in either the context or props of >"Connect(Photos)". Either wrap the root component in a , or >explicitly pass "store" as a prop to "Connect(Photos)".

I used jest and my component is connected to the redux store using

export default connect(mapToProps)(Photos);

AccessoriesPhotos.js

class Photos extends React.Component {
    constructor() {
        super();
        this.state = {
            open: false,

        }
        this.handleOpen = this.handleOpen.bind(this);
    }
    handleOpen = () => {
        this.setState({ open: true });
    };

    render (){
        return (....)
    }

    const mapToProps = (state) => {
        return {
          Search: state.Search,
          App: state.App
        }
      }


    export default connect(mapToProps)(Photos);
}

AccessoriesPhotos.test.js

import React from 'react';
import Enzyme, {shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { Photos } from '../../../Photos/Bike/AccessoriesPhotos';

Enzyme.configure({adapter: new Adapter()});

it('Dialog box opens after click', () => {

  const openDialogButton = shallow(<Photos open="true" close="false" />);

  expect(openDialogButton.text()).toEqual('true');

  openDialogButton.find('input').simulate('change');

  expect(openDialogButton.text()).toEqual('false');
});

This is what I got as the result.

Invariant Violation: Could not find "store" in either the context or props of >"Connect(Photos)". Either wrap the root component in a , or >explicitly pass "store" as a prop to "Connect(Photos)".strong text


Solution

  • Your Photos component doesn't get a store since you are not rendering it as a child to Provider in your test. If you wrap it in a Provider for the test as well it will work as expected.

    const openDialogButton = shallow(
      <Provider store={store}>
        <Photos open="true" close="false" />
      </Provider>
    );