Search code examples
reactjsfirebasereact-nativeunit-testingjestjs

how to mock auth from @react-native-firebase/auth


I am trying to mock the auth module from the npm library @react-native-firebase/auth however, I keep getting this error back. I have tried mocking it below but obviously it must be incorrect I am just unsure on what is incorrect.

TypeError: Cannot read property 'credential' of undefined
jest.mock('@react-native-firebase/auth', () => ({
  auth: {
    GoogleAuthProvider: {
      credential: jest.fn().mockReturnValue('123'),
    },
  },
}));

jest.mock('@react-native-community/google-signin', () => ({
  GoogleSignin: {
    signIn: jest.fn().mockReturnValue('123'),
  },
}));
    import auth from '@react-native-firebase/auth';
    import {GoogleSignin} from '@react-native-community/google-signin';
    
    export const GoogleLogin = async function (): Promise<void | string> {
      // Get the users ID token
      const {idToken} = await GoogleSignin.signIn();
    
      // Create a Google credential with the token
      const googleCredential = auth.GoogleAuthProvider.credential(idToken);
    
      try {
        auth().signInWithCredential(googleCredential);
      } catch (e) {
        console.log(e);
      }
    };


Solution

  • You are mocking @react-native-firebase/auth as if it exported firebase (where the auth namespace is accessed as firebase.auth), but you should be mocking it as if it exported the auth namespace directly.

    In your current mock, you have defined auth.auth.GoogleAuthProvider.credential instead of auth.GoogleAuthProvider.credential.

    jest.mock('@react-native-firebase/auth', () => ({
      GoogleAuthProvider: {
        credential: jest.fn().mockReturnValue('123'),
      },
    }));