如何在 Firebase/应用中测试'auth().signInWithCredential'?



我正在使用firebase/auth和google login with react-native编写测试代码

但是,我的测试代码中总是有bug

我的UI组件在下面。

import { GoogleSignin } from "@react-native-google-signin/google-signin";
import auth from "@react-native-firebase/auth";
let userInfo;
try {
userInfo = await GoogleSignin.signIn();
} catch (error) {
console.error(error);
}
const googleCredential = auth.GoogleAuthProvider.credential(userInfo.idToken);
let testPromise;
try {
testPromise = await auth().signInWithCredential(googleCredential);
} catch (error) {
// In real code environment, there are no problem.
// But, In my test environment, the engine of the code always occur error in here
console.error(error);
}

错误信息如下。

console.error
TypeError: (0 , _auth.default) is not a function

测试代码的mock部分在

下面
jest.mock("@react-native-firebase/auth", () => {
return {
GoogleAuthProvider: {
credential: jest.fn().mockReturnValue({ providerId: "fakeProviderId", secret: "fakeSecret", token: "fakeToken" }),
},
signInWithCredential: jest.fn(),
};
});

里面有一些技巧

我认为我建议的方式不是最佳实践。但是,你可以这样做这个问题。

In react component...
import auth from "@react-native-firebase/auth";
import { firebase } from "@react-native-firebase/auth"; << KEY POINT
test component...
const mockedFbAuth = jest.fn();
jest.mock("@react-native-firebase/auth", () => {
return {
firebase: {
auth: jest.fn().mockImplementation(() => ({
signInWithCredential: mockedFbAuth.mockReturnValue({
additionalUserInfo: {
profile: {
email: "fakeCredentialEmail",
name: "fakeCredentialName",
},
},
}),
})),
},
};
});

以上的方法,我可以解决我的问题!

最新更新