React 测试模拟实现一,使用模拟函数
React testing mock implementation one, work with mocked funcitons
我正在为 firebase 身份验证实现一个模拟函数,我已经像这样模拟了 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 returns 一个用户 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
之前模拟return值。
例如:
auth.createUserWithEmailAndPassword
.mockReturnValueOnce({user: { uid: 'mocked uid'}})
auth.createUserWithEmailAndPassword()
// Insert your expect statement(s) here
...
我正在为 firebase 身份验证实现一个模拟函数,我已经像这样模拟了 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 returns 一个用户 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
之前模拟return值。
例如:
auth.createUserWithEmailAndPassword
.mockReturnValueOnce({user: { uid: 'mocked uid'}})
auth.createUserWithEmailAndPassword()
// Insert your expect statement(s) here
...