最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to test useEffect combined with useDispatch hooks using jestenzyme? - Stack Overflow

programmeradmin4浏览0评论

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

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 (...);
};
Share Improve this question edited Sep 9, 2019 at 17:58 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Sep 9, 2019 at 17:43 Asaf AvivAsaf Aviv 11.8k2 gold badges31 silver badges47 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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

发布评论

评论列表(0)

  1. 暂无评论