0

What is the best approach to test custom hooks, when u are doing component testing and custom hooks dispatch actions and change redux state. For example, I have custom hook which is called on onChange or onClick. I like to simulate the click method, but calling the custom hook, even ends with success and in console.log I can see the changes, checking for the changed state, returns default state.

function useButtonCallback = () => {
  const dispatch = useDispatch();
  return React.useCallback(() => {
   dispatch(...);
  }, [dispatch]);
}
const buttonCallback = useButtonCallback();
<Button onClick={() => buttonCallback(...)}
component.button.onClick();
component.update(); // waiting for re-render
// returns false
expect(store.getState().someState.stateBoolean).toBe(true);

BR,

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • Does this answer your question? [How to test a component using react-redux hooks?](https://stackoverflow.com/questions/56827300/how-to-test-a-component-using-react-redux-hooks) – skyboyer Sep 03 '21 at 21:13
  • in other words - there is no difference if you have custom hook that utilizes `useDispatch` or your component uses `useDispatch` directly, test should be the same. Wrap component with `` and mocked store, trigger click and check whether some expected actions been dispatched on store – skyboyer Sep 03 '21 at 21:14

0 Answers0