我正在尝试模拟react-native-firebase
的firebase.auth对象,以便它将凭证返回给被测代码,以便我可以测试我的方法。
我正在测试以下代码:
public async FacebookSignIn(): Promise<void> {
try {
const result = await LoginManager.logInWithReadPermissions(['public_profile', 'email']);
if (result.isCancelled) {
throw new Error('User cancelled request');
}
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
throw new Error('Something went wrong obtaining the users access token');
}
const credential = firebase.auth.FacebookAuthProvider.credential(data.accessToken);
await firebase.auth().signInWithCredential(credential);
}
catch (error) {
console.error(error);
}
}
我想确保在函数结束时,我的CUT调用signInWithCredential,所以我有一个像这样的测试用例; func
是全局变量:
jest.fn()
describe('FacebookSignIn', () => {
it('should sign in user with facebook credentials', async () => {
await service.FacebookSignIn();
expect(func).toHaveBeenCalled();
})
})
但是,通过以下模拟,我得到了错误TypeError: Cannot read property 'credential' of undefined
:
jest.mock('react-native-firebase', () => {
return {
auth: () => {
return {
currentUser: null,
signOut: func,
signInAnonymously: func,
signInWithEmailAndPassword: func,
signInWithCredential: func,
FacebookAuthProvider: jest.fn(() => {
return {
credential: jest.fn(() => {
return {
provider: 'dummy',
token: '1234',
secret: '5678'
}
})
}
})
}
}
}
});
我已经查看了firebase.auth
的类型,它可以返回以下内容:
type AuthModule = {
(): RNFirebase.auth.Auth;
nativeModuleExists: boolean;
} & RNFirebase.auth.AuthStatics
在我看来,正确地模拟了signIn方法,但是AuthStatics方法并未被模拟。 AuthStatics定义如下:
interface AuthStatics {
EmailAuthProvider: EmailAuthProvider;
PhoneAuthProvider: AuthProvider;
GoogleAuthProvider: AuthProvider;
GithubAuthProvider: AuthProvider;
OAuthProvider: AuthProvider;
TwitterAuthProvider: AuthProvider;
FacebookAuthProvider: AuthProvider;
PhoneAuthState: {
CODE_SENT: string;
AUTO_VERIFY_TIMEOUT: string;
AUTO_VERIFIED: string;
ERROR: string;
};
}
如何模拟FacebookAuthProvider属性,并避免为凭证未定义它?