Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 单元测试用于获取数据、redux useSelector和分派的自定义钩子_Reactjs_Unit Testing_Testing_Redux_React Hooks - Fatal编程技术网

Reactjs 单元测试用于获取数据、redux useSelector和分派的自定义钩子

Reactjs 单元测试用于获取数据、redux useSelector和分派的自定义钩子,reactjs,unit-testing,testing,redux,react-hooks,Reactjs,Unit Testing,Testing,Redux,React Hooks,我一直在测试一个从redux state获取数据的定制钩子,应用程序中的一切都很好,但我在测试覆盖率方面遇到了一些问题,即对我的定制钩子进行单元测试。以下是我的测试代码: useGetHomes自定义挂钩: import { useEffect } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { getHomes } from '../pages/Homes/actions'; co

我一直在测试一个从redux state获取数据的定制钩子,应用程序中的一切都很好,但我在测试覆盖率方面遇到了一些问题,即对我的定制钩子进行单元测试。以下是我的测试代码:

useGetHomes自定义挂钩:

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;
当前测试文件:

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)  

    });

});
从“React”导入React;
从“酶”导入{mount};
从“../useGetHomes”导入useGetHomes;
//用于测试
常量TestHook=({callback})=>{
回调();
返回null;
};
const testHook=callback=>{
mount();
};
//测试结束
描述('useGetHomes',()=>{
让家;
在每个之前(()=>{
testHook(()=>{
homes=useGetHomes();
});
});
它('应该做第一次测试',()=>{
console.log('first test')
控制台日志(主页)
});
});
我当前的测试显示以下错误:

找不到react redux上下文值;请确保组件包装在提供程序中

我尝试将其包装到提供程序中,因为错误很明显,但出现以下错误:

元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象

我想这一点也很清楚,因为定制钩子返回了一个对象,所以我可以做些什么来单元测试我的定制钩子吗?另一方面,我对使用钩子的组件进行的集成测试良好,工作正常。

您有两个选择:

  • 如果要单独测试钩子,请模拟
    useDispatch
    useSelector
  • 如果您想测试钩子如何与将在其中使用的组件交互,请添加一个虚拟组件,其中包含自定义钩子,并使用提供程序等进行包装