'How to write a test for this custom hook using React testing library and Jest

I can't find any material on testing these kind of hooks. Is there any way to mock it and get full test coverage this code? I tried a couple of methods but could not get coverage for the branches as there are conditional statements.

import { Auth } from 'aws-amplify';
import axios from 'axios';
import { useSnackbar } from 'notistack';
import { useNavigate } from 'react-router-dom';

const BASE_URL = 'api';

const useHandleAuthErrorMessage = () => {
  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();

  // const { validateLoginFn } = useValidateLogin();

  const getMessage = async (email: any) => {
    if (email) {
      console.log('🚀 ~ file: useHandleAuthErrorMessage.ts ~ line 32 ~ handleErrorMessage ~ email', email);
      const response = await axios(`${BASE_URL}`, {
        method: 'POST',
        data: {
          email
        }
      });
      const message = response?.data?.data?.message;
      enqueueSnackbar(message, { variant: 'error' });
    }
  };

  const handleErrorMessage = async (error: any, email?: string, password?: string) => {
    if (error.code === 'UserNotConfirmedException') {
      enqueueSnackbar('User is not confirmed.', { variant: 'error' });
      if (email) {
        await Auth.resendSignUp(email);
        navigate('/confirm-signup', { state: { email, password } });
      }
    } else if (error.code === 'NotAuthorizedException') {
      enqueueSnackbar('Username or Password is not correct', { variant: 'error' });
      getMessage(email);
    } else if (error.code === 'UserNotFoundException') {
      enqueueSnackbar('User does not exist', { variant: 'error' });
    } else if (error.code === 'InvalidParameterException') {
      enqueueSnackbar(
        'Cannot reset password for the user as there is no verified email, confirm the user and try again',
        { variant: 'error' }
      );
    } else {
      getMessage(email);
      enqueueSnackbar('Username or Password is not correct', { variant: 'error' });
    }
  };
  return {
    handleErrorMessage
  };
};

export default useHandleAuthErrorMessage;
   


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source