React测试mock实现一,使用mock函数



我正在实现一个用于firebase身份验证的mock函数,我对firebase模块进行了如下模拟:

jest.mock("../../lib/api/firebase", () => {
return {
auth: {
createUserWithEmailAndPassword: jest.fn(() => {
return {
user: {
uid: "fakeuid",
},
};
}),
signOut: jest.fn(),
},
firestore: {
collection: jest.fn(() => ({
doc: jest.fn(() => ({
collection: jest.fn(() => ({
add: jest.fn(),
})),
set: jest.fn(),
})),
})),
},
};
});

现在createUserWithEmailAndPassword返回一个用户uid,以在注册时伪造firebase响应。我在测试中这样使用它:

.
.
.
await wait(() => {
expect(auth.createUserWithEmailAndPassword).toHaveBeenCalled();
expect(history.location.pathname).toBe("/dashboard");
expect(getByText("You succesfully signed up!")).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
...

最新更新