我正在尝试模拟 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呼叫签名符号,以便我有一个类似的测试用例;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
看来它正确地模拟了符号方法,但验证方法没有被模拟。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;
};
}
在尽管您的问题年龄较大,但我偶然发现了同样的挑战,我可以这样解决:
创建项目root auth模块的默认模拟
// file: __mocks__/@react-native-firebase/auth/index.js
const auth = jest.fn().mockReturnValue({
onUserChanged: jest.fn().mockReturnValue(() => {}),
createUserWithEmailAndPassword: jest.fn(),
signInWithCredential: jest.fn(),
// more functions from the module you want to use in your tests
});
auth.FacebookAuthProvider = {
credential: jest.fn(),
};
export default auth;
然后,在您的测试文件中
describe('auth', () => {
let authMock: jest.Mocked<ReturnType<typeof firebaseAuth>>;
let facebookAuthProviderMock: jest.Mocked<FirebaseAuthTypes.AuthProvider>;
beforeEach(() => {
authMock = firebaseAuth() as jest.Mocked<ReturnType<typeof firebaseAuth>>;
facebookAuthProviderMock = firebaseAuth.FaceAuthProviderMock as jest.Mocked<FirebaseAuthTypes.AuthProvider>;
});
it('your test', () => {
// given
authMock.signInWithCredential.mockResolvedValue({});
facebookAuthProviderMock.credential.mockReturnValue({});
// ...
// then
expect(authMock.signInWithCredential).toHaveBeenCalledWith({});
})
})