Why is JEST testing giving "Could not find "store" error when call setState?

Viewed 85

I'm trying to test this: (I need to confirm that when selectedDevice is called with DESKTOP prop, it calls openModal and that method sets the state of modalOpen to true)

  openModal = () => {
    this.setState({ modalOpen: true });
  };


  selectedDevice = () => {
    const { device } = this.props;
    const isMobile = device === MOBILE;
    if (isMobile) {
      this.closeWindow();
    } else {
      this.openModal();
    }
  };

and I'm testing like this (with JEST)

test('should openModal be called', () => {
    const wrapper = mount(<Component
      {...sampleProps}
      deviceType={DESKTOP}
    />);

    const selectedDevice = jest.spyOn(wrapper.instance(), 'selectedDevice');
    selectedDevice();
    expect(wrapper.state().modalActivated).toEqual(true);
  });

Apparently, it seems to be reaching the openModal method in my component. However, I'm getting this error:

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

      36 | 
      37 |   openModal = () => {
    > 38 |     this.setState({ modalOpen: true });
         |          ^

I saw another solutions to that error message, but nothing seems to work for this specific error. I already tried wrapping the component inside a Provider component with no luck.

1 Answers

You're getting the error because you're using a component which is wrapped inside of the connect HOC from react-redux and the connect HOC needs the redux Provider component with a state.

Your code should be something like this:

test("should openModal be called", () => {
  const wrapper = mount(
    <Provider store={CreateANewStoreForTest}>
      <Component {...sampleProps} deviceType={DESKTOP} />
    </Provider>
  );

  const selectedDevice = jest.spyOn(wrapper.instance(), "selectedDevice");
  selectedDevice();
  expect(wrapper.state().modalActivated).toEqual(true);
});

and for data on how to create a store read the DOC here

Related