I don't seem to find a solution for the below code / test to work (I went through a lot of articles and stackOverflow...). Various solutions provided by chatGPT are useless as well. I also see people telling that you should never mock hooks. So my question is: should I just forget it because it's not the best practice anyway?
P.S. This code is from the course I am following at Zero to Mastery, however, I am using Vite with Vitest instead of Create-React-App and Jest which are used in the course. In this particular lesson teacher was showing the workaround when sagas are involved, and that's why the idea is to spy on useDispatch instead of using fire.Event + store.getState....
test('it should dispatch signOutStart action when clicking on Sign Out link', async () => {
const mockDispatch = vi.fn();
vi.spyOn(reactRedux, 'useDispatch').mockReturnValue(mockDispatch);
renderWithProviders(<Navigation />, {
preloadedState: {
user: {
currentUser: {}
}
}
});
const signOutLinkElement = screen.getByText(/sign out/i);
expect(signOutLinkElement).toBeInTheDocument();
await fireEvent.click(signOutLinkElement);
expect(mockDispatch).toHaveBeenCalled();
expect(mockDispatch).toHaveBeenCalledWith(signOutStart());
mockDispatch.mockClear();
})
dispatchis an internal implementation detail. You are already rendering the component-under-test within a Redux provider, so why not just assert that thesignOutStartfunction was called? It's the code you technically own, right?const spy = vi.spyOn(userActions, 'signOutStart'); + expect(spy).toHaveBeenCalled();