jest mock TypeError: Cannot read property 'credential' of undefined on library react-native-firebase

Viewed 514

I am using react-native and am unable to mock credentials from the library react-native-firebase.

TypeError: Cannot read property 'credential' of undefined

will keep appearing even though I think I am mocking credentials correctly.

import {GoogleLogin} from './GoogleLogin';

const mocks = {
  auth: jest.fn(),
  signInWithCredential: jest.fn(),
  GoogleAuthProvider: {
    credential: jest.fn(),
  },
};

Object.defineProperty(mocks.auth, 'GoogleAuthProvider', {
  value: mocks.GoogleAuthProvider,
});

mocks.auth.mockReturnValue({
  signInWithCredential: mocks.signInWithCredential,
});

mocks.GoogleAuthProvider.credential.mockReturnValue({
  providerId: 'string',
  token: '123',
  secret: 'string',
});

jest.mock('@react-native-firebase/auth', () => {
  return () => mocks.auth;
});

jest.mock('@react-native-community/google-signin', () => ({
  GoogleSignin: {
    signIn: jest.fn().mockReturnValue('123'),
  },
}));

describe('navigation > auth > GoogleLogin', () => {
  it('calls signInWithCredential', async () => {
    await GoogleLogin();
    expect(mocks.signInWithCredential).toHaveBeenCalled();
  });
});
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);
  }
};
1 Answers

credential is a method on GoogleAuthProvider and GoogleAuthProvider is a method on auth so mocking it should look something like this:

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

or

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

should also work fine

Related