【发布时间】:2021-10-31 03:05:17
【问题描述】:
我使用 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() 应该没问题,但它仍然有错误。
我是测试领域的新手。请有人对此提出一些建议并告诉我我的测试有什么问题?我完全不知道
在寻找这个answer之后,我试图像这样模拟它:
const mockSomething = jest.fn().mockImplementation(() => Promise.resolve({
user: {
uid: "fakeuid",
},
}))
但还是有同样的错误
【问题讨论】:
标签: reactjs firebase jestjs react-testing-library react-hooks-testing-library