我如何测试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 (...);
};
答案 0 :(得分:3)
首先,我们使用jest.mock
来模拟useDispatch
:
import { useDispatch, useShallowEqualSelector } from 'react-redux';
jest.mock('react-redux');
第二,我们用mount
(shallow
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,
});
});