reactjs - 开玩笑的模拟 TypeError:无法读取库 react-native-firebase 上未定义的属性“凭据”
问题描述
我正在使用 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);
}
};
解决方案
credential
是一个方法GoogleAuthProvider
,GoogleAuthProvider
是一个方法,auth
所以模拟它应该看起来像这样:
jest.mock('@react-native-firebase/auth', () => ({
GoogleAuthProvider: {
credential: jest.fn().mockReturnValue('some credential'),
},
}));
或者
jest.mock('@react-native-firebase/auth', () => ({
GoogleAuthProvider: {
credential: jest.fn(),
},
}));
也应该可以正常工作