How to write mocks for Google Sign In Async await Callbacks with jest enzyme and perform Unit Testing in react-native?

Viewed 496

I have a class GoogleSign.js

import {GoogleSignin, statusCodes} from '@react-native-community/google-signin';
import React, {useEffect} from 'react';
import {Text, View, TouchableOpacity, Image, Alert} from 'react-native';
import {RFValue} from 'react-native-responsive-fontsize';
 
import ColorConstants from '../../constants/ColorConstants';
import ImageConstants from '../../constants/ImageConstants';
import {Fonts} from '../../constants/Constants';
import {verticalScale} from '../../helpers/Functions';
import {WEB_CLIENT_ID} from '../../utils/keys.js';
 
const GoogleMainButton = ({text, onPress, parentCallback}) => {
  const googleLoginStyle = {
    backgroundColor: ColorConstants.white,
    borderRadius: 8,
    marginBottom: 8,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: verticalScale(40),
  };
 
  const textGoogleStyle = {
    color: ColorConstants.black,
    fontSize: RFValue(16),
    textAlign: 'center',
    fontFamily: Fonts.InterSemibold,
    paddingVertical: 10,
  };
 
  const _isSignedIn = async (userInfo, errorCallBack) => {
    await GoogleSignin.isSignedIn().then((isSignedIn) => {
      if (isSignedIn) {
        // Alert.alert('User is already signed in');
        getCurrentUserInfo(
          (result) => {
            userInfo(result);
          },
          (error) => {
            errorCallBack(error);
          },
        );
      } else {
        //Alert.alert('Please Login');
        signIn(
          (result) => {
            userInfo(result);
          },
          (error) => {
            errorCallBack(error);
          },
        );
      }
    });
  };
 
  const getCurrentUserInfo = async (result, errorCallBack) => {
    try {
      await GoogleSignin.signInSilently().then((res) => {
        result(res.user);
      });
    } catch (error) {
      errorCallBack(error);
      if (error.code === statusCodes.SIGN_IN_REQUIRED) {
        // when user hasn't signed in yet
      } else {
        Alert.alert('Something else went wrong... ', error.toString());
        // this.setState({isLoggedIn: false});
      }
    }
  };
 
  const signIn = async (userInfoCallBack, errorCallBack) => {
    try {
      await GoogleSignin.hasPlayServices().then(async (res) => {
        if (res) {
          await GoogleSignin.signIn().then((result) => {
            userInfoCallBack(result.user);
          });
        }
      });
    } catch (error) {
      errorCallBack(error);
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        // when user cancels sign in process,
        Alert.alert('Process Cancelled');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        // when in progress already
        Alert.alert('Process in progress');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        // when play services not available
        Alert.alert('Play services are not available');
      } else {
        // some other error
        Alert.alert('Something else went wrong... ', error.code.toString());
      }
    }
  };
 
  const googleLoginButton = (props) => {
    useEffect(() => {
      GoogleSignin.configure({
        webClientId: WEB_CLIENT_ID,
        offlineAccess: false,
      });
    }, []);
    return (
      <TouchableOpacity
        onPress={() => {
          _isSignedIn(
            (res) => {
              parentCallback({response: res});
            },
            (error) => {
              console.log(error);
            },
          );
        }}>
        <View style={googleLoginStyle}>
          <Image source={ImageConstants.googleLogo} />
          <Text style={[textGoogleStyle]}> {props.text} </Text>
        </View>
      </TouchableOpacity>
    );
  };
 
  return googleLoginButton({text, onPress, parentCallback});
};
 
export default GoogleMainButton;

Also I have I mock class google-signin.ts inside @react-native-community folder which is inside mocks folder

it('mock google login', () => {
  jest.mock('@react-native-community/google-signin', () => {});
});

And I have a class GoogleSignIn.test.js In this class I have used the code to match the snapshot and have simulated the button click.

import 'react-native';
import React from 'react';
import GoogleSignin from '../src/components/utilities/PrimaryGoogleSignIn';

import {shallow, render, mount} from 'enzyme';

it('renders correctly', () => {
  const mockFunc = jest.fn();
  const info = {};

  const wrapper = shallow(<GoogleSignin parentCallback={mockFunc} />);
  wrapper.dive().simulate('press');
  expect(wrapper).toMatchSnapshot();
  //expect(mockFunc).toHaveBeenCalledTimes(1);
});

So the problem is here I am not able to complete it's unit testing to 100% the percentage it is covering is near to 29.

I have written few lines of code for unit testing which I guess works till the simulation of onPress.
I am not able get the full coverage.

enter image description here enter image description here enter image description hereenter image description here

As I am new to Unit testing. Please I need help.

0 Answers
Related