Asa*_*viv 3 javascript reactjs jestjs enzyme react-redux
如何测试是否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 (...);
};
Run Code Online (Sandbox Code Playgroud)
首先,我们jest.mock用来被useDispatch嘲笑:
import { useDispatch, useShallowEqualSelector } from 'react-redux';
jest.mock('react-redux');
Run Code Online (Sandbox Code Playgroud)
其次,我们使用mount(shallow 不运行,useEffect因为 React 自己的浅层渲染器不这样做)渲染我们的元素。
const wrapper = mount(<MoviesShowcaseList />);
Run Code Online (Sandbox Code Playgroud)
如果使用现代版本的酶,我们不需要做任何额外的事情,act()因为它已经在 Enzyme 中了。
最后我们检查是否useDispatch已被调用:
expect(useDispatch).toHaveBeenCalledWith({
type: MoviesTypes.REQUEST_MOVIES,
0,
});
Run Code Online (Sandbox Code Playgroud)
一起(带有嘲讽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,
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6955 次 |
| 最近记录: |