如何使用玩笑/酶测试结合使用useDispatch挂钩的useEffect? [英] How to test useEffect combined with useDispatch hooks using jest/enzyme?
本文介绍了如何使用玩笑/酶测试结合使用useDispatch挂钩的useEffect?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 requestMovies $ c $测试
useEffect
是否调用 dispatch
c>正在装载?
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 (...);
};
推荐答案
首先,我们使用 jest.mock
以获得 useDispatch
模拟:
First, we use jest.mock
to get useDispatch
mocked:
import { useDispatch, useShallowEqualSelector } from 'react-redux';
jest.mock('react-redux');
第二,我们用 mount
渲染元素(浅
不运行 useEffect
,因为React自己的浅层渲染器不这样做)。
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 />);
如果使用现代版本的酶,则无需对 act()
,因为它已经已加入酶。
If using modern version of enzyme we don't need to do anything additional with act()
since it's already in Enzyme.
最后,我们检查是否已调用 useDispatch
:
And finally we check if useDispatch
has been called:
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,
});
});
这篇关于如何使用玩笑/酶测试结合使用useDispatch挂钩的useEffect?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文