在测试用例中编写Jest模拟时,请遵循DRY原理-React和Jest

问题描述

我是测试的新手,我想在单元测试用例中遵循DRY原则。在我的测试用例中,我在模拟react-redux的useSelector和useDispatch,并且当前在所有使用react-redux的测试中都编写相同的模拟。以下是我的测试用例之一。

import React from 'react';
import { shallow } from 'enzyme';
import LayoutComponent from './LayoutComponent';


const mockDispatch = jest.fn();
jest.mock('react-redux',() => ({
    ...jest.requireActual('react-redux'),useSelector: jest.fn(),useDispatch: () => mockDispatch
}));

const setup = () => {
    return shallow(<LayoutComponent />)
}

const mockState = (state) => {
    return useSelector.mockImplementationOnce(callback => {
        return callback(state);
    })
}

jest.mock("react-router-dom",() => ({
    ...jest.requireActual("react-router-dom"),useLocation: () => ({
        pathname: "localhost:3000/"
    })
}));

describe('LayoutComponent',() => {
    afterEach(() => {
        jest.clearAllMocks();
    })
    test('Calls getUserInfo on mount',() => {
        setup();
        expect(mockDispatch).toHaveBeenCalledWith(expect.any(Function));
expect(mockDispatch).toHaveBeenCalledTimes(1);
    });

});

我不想在所有测试文件中编写该模拟,而是希望将react-redux模拟保持单独,以便可以将其导入所有使用这些文件的文件中,而无需一次又一次地编写它们。

有人可以帮我吗?预先谢谢你。

更新

我已经在__mocks__文件夹旁边和node_modules文件夹中创建了一个名为__mocks__的目录,我已经创建了react-redux.js文件。在文件中,具有以下模拟功能。

const mockDispatch = jest.fn()

module.exports = {
    ...jest.requireActual('react-redux'),__esModule: true,useDispatch: () => mockDispatch,mockDispath,};

下面是测试

import React from 'react';
import { shallow } from 'enzyme';
import ResolutionCount from '../ResolutionCount';
import { mockDispatch,mockState } from 'react-redux';

const setup = props => {
    return shallow(<ResolutionCount componentUsedIn={props} />)
}

describe("ResolutionCount component",() => {
    test("testing component with prop value",() => {
        mockState({
            userInfoReducer: {
                userInfo: [
                    {
                        user_id: 'some id',user_name: 'some name',user_email: 'someemail@email.com',user_pic: null,is_admin: true,is_super_user: false,},]
            }
        });

        setup("my resolutions");

        expect(mockDispatch).toHaveBeenCalledWith({
            type: "SET_RESOLUTION_STATUS_COUNT_BAR_CHART_FETCHING_DATA",payload: true,});

    })
})

所以现在当我运行测试时,我得到了错误提示

TypeError: (0,_reactRedux.mockState) is not a function
 describe("ResolutionCount component",() => {
      11 |     test("testing component with prop value",() => {
    > 12 |         mockState({
         |         ^
      13 |             userInfoReducer: {
      14 |                 userInfo: [
      15 |                     {

Error

Folder structure

解决方法

__mocks__目录中的可重用模拟是Jest为此提供的一种方式。

如果需要直接访问间谍以修改实现或声明其实现,则可以将其添加到模块导出中,必须使用前缀mock否则避免与现有导出的名称冲突。

/ __ mocks __ / react-redux.js

const mockDispatch = jest.fn();

module.exports = {
    ...jest.requireActual('react-redux'),__esModule: true,useSelector: jest.fn(),useDispatch: jest.fn(() => mockDispatch),mockDispatch
};

该模拟程序应在导入时自动应用。然后可以像往常一样将mockDispatch导入测试中:

import { mockDispatch } from 'react-redux';

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...