0

I have been testing a custom hook for getting data from redux state and all is working nice within the app but I am having some issues with testing coverage, namely with unit testing my custom hook. here is my testing code:

useGetHomes custom hook:

import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';

import { getHomes } from '../pages/Homes/actions';

const useGetHomes = () => {

   const dispatch = useDispatch();
   const homes = useSelector(state => state.homes);

   useEffect(() => {

       dispatch(getHomes()); 

   }, [dispatch]);

   //TO DO - extend more

   return {
      homes
   };

};

export default useGetHomes;

current test file:

import React from 'react';
import { mount } from 'enzyme';

import useGetHomes from '../useGetHomes';

//for testing
const TestHook = ({callback}) => {

    callback();
    return null;

};

const testHook = callback => {
  mount(<TestHook callback={callback}/>);
};
//end for testing

describe('useGetHomes', () => {

    let homes;

    beforeEach(() => {
        testHook(() => {
            homes = useGetHomes();
        });
    });

    it('should do first test', () => {

        console.log('first test')
        console.log(homes)  

    });

});

my current test gives me the following error:

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

I tried wrapping it in a Provider as error is clear but I get the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

I guess this is also clear as custom hook returns an object, so is there anything I could do to unit test my custom hook ? On the other hand my integration tests on the components that use the hook are good and working properly.

user1751287
  • 491
  • 9
  • 26
  • Does this answer your question? [How can I test a custom hook that is using the Redux hooks useDispatch and useSelector?](https://stackoverflow.com/questions/59442450/how-can-i-test-a-custom-hook-that-is-using-the-redux-hooks-usedispatch-and-usese) – Liam May 19 '23 at 09:43

1 Answers1

2

For anyone looking for a solution to this now, @testing-library/react offers a solution: https://react-hooks-testing-library.com/usage/advanced-hooks

Redux is simply a React Context, so the above strategy should work for testing a hook that requires any type of provider, be it a custom one in your app, redux, or a drag drop context.

pskfry
  • 66
  • 5