Reactjs React测试模拟实现一,使用模拟函数
我正在为firebase身份验证实现模拟功能,我模拟了firebase模块,如下所示:Reactjs React测试模拟实现一,使用模拟函数,reactjs,firebase,jestjs,react-testing-library,Reactjs,Firebase,Jestjs,React Testing Library,我正在为firebase身份验证实现模拟功能,我模拟了firebase模块,如下所示: auth.createUserWithEmailAndPassword .mockReturnValueOnce(/* your desired return value here */) jest.mock(“../../lib/api/firebase)”,()=>{ 返回{ 认证:{ createUserWithEmailAndPassword:jest.fn(()=>{ 返回{ 用户:{ uid:“
auth.createUserWithEmailAndPassword
.mockReturnValueOnce(/* your desired return value here */)
jest.mock(“../../lib/api/firebase)”,()=>{
返回{
认证:{
createUserWithEmailAndPassword:jest.fn(()=>{
返回{
用户:{
uid:“fakeuid”,
},
};
}),
签出:jest.fn(),
},
firestore:{
集合:jest.fn(()=>({
文件:jest.fn(()=>({
集合:jest.fn(()=>({
添加:jest.fn(),
})),
set:jest.fn(),
})),
})),
},
};
});
现在createUserWithEmailAndPassword返回一个用户uid,以在注册时伪造firebase响应。我在测试中使用它,如下所示:
auth.createUserWithEmailAndPassword
.mockReturnValueOnce(/* your desired return value here */)
。
.
.
等待等待(()=>{
期望(auth.createUserWithEmailAndPassword).toHaveBeenCalled();
expect(history.location.pathname).toBe(“/dashboard”);
expect(getByText(“您成功注册了!”).toBeInTheDocument();
});
它工作得非常好,但是如果我希望返回的值在一次测试中有所不同,该怎么办呢?
我看到了mockImplementationOnce,这似乎是正确的方法,但我正在努力实现它,有什么帮助吗?
谢谢
F.您可以像这样使用
mockReturnValueOnce
:
auth.createUserWithEmailAndPassword
.mockReturnValueOnce(/* your desired return value here */)
在测试中调用auth.createUserWithEmailAndPassword
之前,请确保您正在模拟返回值
例如:
auth.createUserWithEmailAndPassword
.mockReturnValueOnce({user: { uid: 'mocked uid'}})
auth.createUserWithEmailAndPassword()
// Insert your expect statement(s) here
...
是的,我也想到了,我只是有一些来自typescript的警告