reactjs - React 测试模拟实现一,使用模拟函数
问题描述
我正在实现一个用于 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返回一个用户 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
...
推荐阅读
- html - Don't working vertical alignment of img in div css
- php - 在 Wordpress 中使用 WP_Query 在循环中显示帖子时遇到问题
- node.js - 在后端解析对象数组时出现问题。被nodeJS解析为[Object Object]
- javascript - 检查页面中是否呈现了 javascript DOM 元素
- jasmine - 如何在 Protractor 中使用 Jasmine 3.3 或更高版本?
- neo4j - Neo4J子查询相同的属性来计算比率
- reactjs - Expect 不是反应测试库中的函数
- angularjs - 有没有办法在新的角度应用程序中找到pendingReuests
- machine-learning - 不完整数据的均值居中
- javascript - CSS - 模糊 div 内的模糊 div 问题