Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dispatch is not a function - React Testing Library with React Redux Hooks

I want to test if the component is dispatching an action to the store, for this, i have to mock the functionalities of React Hooks.

I'm using the useDispatch hook to get the dispatcher function and put inside a variable so them i can call it.

When i run my test suits, even if the useDispatch function is mocked, it returns an error saying that it's not a function.

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'));
});

The error:

    TypeError: dispatch is not a function

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

My component:

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;
  }
like image 653
Laura Beatris Avatar asked Oct 17 '25 19:10

Laura Beatris


1 Answers

The component was trying to execute a function that wasn't declared yet. We need to mock before of the render method

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

const dropdown = render(<Dropdown />);
like image 103
Laura Beatris Avatar answered Oct 20 '25 08:10

Laura Beatris