如何使用玩笑/酶测试结合使用useDispatch挂钩的useEffect?

时间:2019-09-09 17:43:16

标签: javascript reactjs react-redux jestjs enzyme

我如何测试useEffect是否在挂载dispatch的情况下呼叫requestMovies

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 个答案:

答案 0 :(得分:3)

首先,我们使用jest.mock来模拟useDispatch

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

jest.mock('react-redux');

第二,我们用mountshallow does not run useEffect渲染元素,因为React自己的浅层渲染器不这样做)。

const wrapper = mount(<MoviesShowcaseList />);

如果使用现代版本的酶,我们不需要对act()做任何额外的操作,因为它是already in Enzyme

最后,我们检查是否调用了useDispatch

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

一起(连同嘲笑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,
  });
});