Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing custom hook: Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a <Provider>

I got a custom hook which I want to test. It receives a redux store dispatch function and returns a function. In order to get the result I'm trying to do:

const { result } = renderHook(() => { useSaveAuthenticationDataToStorages(useDispatch())});

However, I get an error:

Invariant Violation: could not find react-redux context value; please ensure the component is wrapped in a

It happens because of the useDispatch and that there is no store connected. However, I don't have any component here to wrap with a provider.. I just need to test the hook which is simply saving data to a store.

How can I fix it?

like image 865
Yonatan Nir Avatar asked Dec 25 '19 09:12

Yonatan Nir


2 Answers

The react hooks testing library docs go more into depth on this. However, what we essentially are missing is the provider which we can obtain by creating a wrapper. First we declare a component which will be our provider:

import { Provider } from 'react-redux'

const ReduxProvider = ({ children, reduxStore }) => (
  <Provider store={reduxStore}>{children}</Provider>
)

then in our test we call

test("...", () => {
  const store = configureStore();
  const wrapper = ({ children }) => (
    <ReduxProvider reduxStore={store}>{children}</ReduxProvider>
  );
  const { result } = renderHook(() => {
    useSaveAuthenticationDataToStorages(useDispatch());
  }, { wrapper });
  // ... Rest of the logic
});
like image 154
Jose Felix Avatar answered Nov 15 '22 04:11

Jose Felix


This is probably a late answer but you can also use this in your test

jest.mock('react-redux', () => {
    const ActualReactRedux = jest.requireActual('react-redux');
    return {
        ...ActualReactRedux,
        useSelector: jest.fn().mockImplementation(() => {
            return mockState;
        }),
    };
});
like image 14
hungneox Avatar answered Nov 15 '22 03:11

hungneox