【问题标题】:jest mock TypeError: Cannot read property 'credential' of undefined on library react-native-firebase开玩笑的模拟 TypeError:无法读取库 react-native-firebase 上未定义的属性“凭据”
【发布时间】:2021-03-01 15:22:34
【问题描述】:

我正在使用 react-native,无法模拟来自库 react-native-firebase 的凭据。

TypeError:无法读取未定义的属性“凭据”

即使我认为我正确地模拟了凭据,也会继续出现。

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

【问题讨论】:

    标签: reactjs react-native unit-testing jestjs mocking


    【解决方案1】:

    credentialGoogleAuthProvider 上的一个方法,GoogleAuthProviderauth 上的一个方法,所以模拟它应该看起来像这样:

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

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

    应该也能正常工作

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2018-06-17
      • 1970-01-01
      • 2023-03-03
      • 2020-07-10
      • 2017-12-15
      • 1970-01-01
      • 2020-06-26
      • 2017-10-18
      相关资源
      最近更新 更多