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

neskvpey  于 2024-01-04  发布在  Jest
关注(0)|答案(2)|浏览(201)

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

  1. TypeError: Cannot read property 'credential' of undefined
  1. jest.mock('@react-native-firebase/auth', () => ({
  2. auth: {
  3. GoogleAuthProvider: {
  4. credential: jest.fn().mockReturnValue('123'),
  5. },
  6. },
  7. }));
  8. jest.mock('@react-native-community/google-signin', () => ({
  9. GoogleSignin: {
  10. signIn: jest.fn().mockReturnValue('123'),
  11. },
  12. }));
  1. import auth from '@react-native-firebase/auth';
  2. import {GoogleSignin} from '@react-native-community/google-signin';
  3. export const GoogleLogin = async function (): Promise<void | string> {
  4. // Get the users ID token
  5. const {idToken} = await GoogleSignin.signIn();
  6. // Create a Google credential with the token
  7. const googleCredential = auth.GoogleAuthProvider.credential(idToken);
  8. try {
  9. auth().signInWithCredential(googleCredential);
  10. } catch (e) {
  11. console.log(e);
  12. }
  13. };
jckbn6z7

jckbn6z71#

您模拟@react-native-firebase/auth,就好像它导出了firebase(其中auth命名空间作为firebase.auth访问),但您应该模拟它,就好像它直接导出了auth命名空间。
在当前的模拟中,您定义了auth.auth.GoogleAuthProvider.credential而不是auth.GoogleAuthProvider.credential

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

字符串

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中导出模块

  1. // auth.ts
  2. import auth, { firebase } from '@react-native-firebase/auth'; // THE KEYPOINT HERE
  3. import {GoogleSignin} from '@react-native-community/google-signin';
  4. export const GoogleLogin = async function (): Promise<void | string> {
  5. // Get the users ID token
  6. const {idToken} = await GoogleSignin.signIn();
  7. // Create a Google credential with the token
  8. const googleCredential = auth.GoogleAuthProvider.credential(idToken);
  9. try {
  10. firebase.auth().signInWithCredential(googleCredential); // THIS DID TRICK
  11. } catch (e) {
  12. console.log(e);
  13. }
  14. };

个字符

展开查看全部

相关问题