Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test useEffect combined with useDispatch hooks using jest/enzyme?

How can i test if useEffect called dispatch with requestMovies on mount?

import { useDispatch } from 'react-redux';

export const requestMovies = page => ({
  type: MoviesTypes.REQUEST_MOVIES,
  page,
});

const MoviesShowcaseList = () => {
  const { page } = useShallowEqualSelector(state => state.movies);
  const dispatch = useDispatch();

  const fetchNextMoviesPage = () => {
    dispatch(requestMovies(page + 1));
  };

  useEffect(fetchNextMoviesPage, []);

  return (...);
};
like image 703
Asaf Aviv Avatar asked Dec 07 '25 05:12

Asaf Aviv


1 Answers

First, we use jest.mock to get useDispatch mocked:

import { useDispatch, useShallowEqualSelector } from 'react-redux';

jest.mock('react-redux');

Second, we render our element with mount(shallow does not run useEffect since React's own shallow renderer does not do that).

const wrapper = mount(<MoviesShowcaseList />);

If using modern version of enzyme we don't need to do anything additional with act() since it's already in Enzyme.

And finally we check if useDispatch has been called:

expect(useDispatch).toHaveBeenCalledWith({
  type: MoviesTypes.REQUEST_MOVIES,
  0,
});

All together(with mocking useShallowEqualSelector):

import { useDispatch } from 'react-redux';

jest.mock('react-redux');

it('loads first page on init', () => {
  useShallowEqualSelector.mockReturnValueOnce(0); // if we have only one selector
  const wrapper = mount(<MoviesShowcaseList />);
  expect(useDispatch).toHaveBeenCalledTimes(1);
  expect(useDispatch).toHaveBeenCalledWith({
    type: MoviesTypes.REQUEST_MOVIES,
    0,
  });
});

like image 134
skyboyer Avatar answered Dec 08 '25 20:12

skyboyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!