lundi 9 novembre 2020

unit testing custom hook for getting data, redux useSelector and dispatch

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.

Aucun commentaire:

Enregistrer un commentaire