javascript - Dispatch 不是函数 - 带有 React Redux Hooks 的 React 测试库

标签 javascript reactjs redux react-redux react-testing-library

我想测试组件是否正在向商店发送 Action ,为此,我必须模拟 React Hooks 的功能。

我正在使用 useDispatch Hook 来获取调度程序函数并将其放入一个变量中,以便我可以调用它。

当我运行我的测试套件时,即使 useDispatch 函数被模拟,它也会返回一个错误,指出它不是一个函数。

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

it('should be able open modal', () => {
  const { getByTestId } = render(<Dropdown />);

  fireEvent.click(getByTestId('dropdown'));
  fireEvent.click(getByTestId('button-Transactions'));

  const dispatch = jest.fn();
  useDispatch.mockReturnValue(dispatch);

  expect(dispatch).toHaveBeenCalledWith(openModal('transactions'));
});

错误:
    TypeError: dispatch is not a function

      19 | 
      20 |     if (item.action) {
    > 21 |       dispatch(item.action);
         |       ^
      22 |     }
      23 | 
      24 |     return item;

我的组件:
const history = useHistory();
  const dispatch = useDispatch();

  function handleNavigation(item) {
    if (item.path) return history.push(item.path);

    if (item.action) {
      dispatch(item.action);
    }

    return item;
  }

最佳答案

该组件试图执行一个尚未声明的函数。
我们需要在渲染方法之前模拟

const dispatch = jest.fn();
useDispatch.mockReturnValue(jest.fn());

const dropdown = render(<Dropdown />);

关于javascript - Dispatch 不是函数 - 带有 React Redux Hooks 的 React 测试库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61125740/

相关文章:

javascript - 链接不适用于图像?

javascript - axios/Ajax发布数据问题

javascript - 为实用方法提供 Redux 存储

php - 来自 Twitter 的新日期格式

javascript - 在 Vue js 中使用 Sweet Alert 删除确认

node.js - WebSocket 已经处于 CLOSING 或 CLOSED 状态 Socket io

reactjs - Redux:请求成功或来自组件的错误(使用redux-saga)

redux - combineReducers 可以处理额外的 Action 吗?

javascript - 变量数据错误

reactjs - WebStorm 上的 %PUBLIC_URL% 编辑器警告