我使用 Firebase 身份验证,我想使用 Jest 和 react-hooks-testing-library 测试该功能。
我有一个这样的功能:
const loginWithEmailPassword = (email: string, password: string) => {
const auth = getAuth()
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ...
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
});
}
该signInWithEmailPassword()
函数有一个then()
和catch()
块。
我用这段代码模拟了这个函数:
const mockSignUp = jest.fn(() => {
return Promise.resolve({
user: {
uid: "fakeuid",
},
});
})
jest.mock('firebase/auth', () => ({
getAuth: () => mockGetAuth,
signInWithEmailAndPassword: () => mockSignIn,
createUserWithEmailAndPassword: () => mockSignUp
}))
然后我用react-hooks-testing-library
这样的方法测试上面的函数:
test('Login with Email and Password', () => {
const { result } = renderHook(() => useFirebaseAuth())
const email = 'abc@gmail.com'
const password = '123456'
// here fired my loginWithEmailPassword above
act(() => {
// the problem come from this line
result.current.loginWithEmailPassword(email, password)
})
然后我的测试因此错误而失败:
TypeError: (0 , _auth.signInWithEmailAndPassword)(...).then is not a function
46 |
47 | signInWithEmailAndPassword(auth, email, password)
> 48 | .then((userCredential) => {
如果我删除then
块,测试通过。但是如果我使用调用then()
函数它会得到错误。我检查了我的模拟signInWithEmailAndPassword
返回Promise.resolve()
应该没问题,但它仍然有错误。
我是测试领域的新手。请有人对此提出一些建议并告诉我我的测试有什么问题?我完全不知道
在寻找这个答案之后,我试图像这样模拟它:
const mockSomething = jest.fn().mockImplementation(() => Promise.resolve({
user: {
uid: "fakeuid",
},
}))
但仍然有同样的错误