我想测试组件是否正在向商店发送 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/