如何从 @react-native-firebase/auth 模拟身份验证

Rob*_*ins 2 unit-testing firebase reactjs jestjs react-native

我试图从 npm 库 @react-native-firebase/auth 模拟 auth 模块,但是,我不断收到此错误。我尝试在下面嘲笑它,但显然它一定是不正确的,我只是不确定什么是不正确的。

TypeError: Cannot read property 'credential' of undefined
Run Code Online (Sandbox Code Playgroud)
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'),
  },
}));
Run Code Online (Sandbox Code Playgroud)
    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);
      }
    };

Run Code Online (Sandbox Code Playgroud)

sam*_*man 5

您正在模拟@react-native-firebase/auth它,就像它导出一样firebase(其中auth命名空间作为 访问firebase.auth),但您应该模拟它,就好像它auth直接导出命名空间一样。

在当前的模拟中,您已定义auth.auth.GoogleAuthProvider.credential而不是auth.GoogleAuthProvider.credential.

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