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 (...);
};
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,
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With