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

我们两清 提交于 2019-12-22 10:44:45

问题


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 (...);
};

回答1:


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



来源:https://stackoverflow.com/questions/57858836/how-to-test-useeffect-combined-with-usedispatch-hooks-using-jest-enzyme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!