Jest.js 如何从@react-native-firebase/auth模拟验证

neskvpey  于 9个月前  发布在  Jest
关注(0)|答案(2)|浏览(140)

我试图从npm库@react-native-firebase/auth中模拟auth模块,但是,我一直得到这个错误。我已经尝试在下面模拟它,但显然它肯定是不正确的,我只是不确定什么是不正确的。

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);
      }
    };
jckbn6z7

jckbn6z71#

您模拟@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'),
  },
}));

字符串

nhaq1z21

nhaq1z212#

现有的答案没有涵盖如何模拟auth().signInWithCredential。我已经更新了下面的答案。
它使用了来自'@react-native-firebase/auth'authdefault export,并模拟了auth().signInWithCredential()。然而,正确的方法是使用来自'@react-native-firebase/auth'firebase的命名export和模拟firebase.auth().signInWithCredential()
您可以看到@react-native-firebase/auth如何在此script中导出模块

// auth.ts
import auth, { firebase } from '@react-native-firebase/auth'; // THE KEYPOINT HERE
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 {
    firebase.auth().signInWithCredential(googleCredential); // THIS DID TRICK
  } catch (e) {
    console.log(e);
  }
};

个字符

相关问题