node.js - Jest + MockImplementationOnce + 没有第二次工作
问题描述
我正在使用 JEST 框架对我的 node.js 项目进行单元测试。我使用 mockImplementationOnce 来模拟第三方库方法,如下所示: jest.mock('abc', () => { return { a: { b: jest.fn() } }; }); 常量 abcjs= 要求('abc');
describe("1st test", () => {
test("should return true", async () => {
abcjs.a.b.mockImplementationOnce(() => Promise.resolve(
return true}
));
});
});
describe("2nd test", () => {
test("should return false", async () => {
abcjs.a.b.mockImplementationOnce(() => Promise.resolve(
return false}
));
});
});
第一个测试成功执行,但第二个测试它调用实际方法,它不是模拟。 我尝试在 afterEach 之后重置模拟,但没有帮助。
解决方案
昨天我在模拟 aws-sdk 时遇到了同样的问题。
事实证明,在你模拟了整个模块一次之后,你不能再次覆盖同一个文件中那个模拟的行为。
我很惊讶您的第一个测试实际上通过了,即使您的默认模拟函数只是一个没有任何返回值的 jest.fn()。
这里有一个完整的讨论 - https://github.com/facebook/jest/issues/2582
来自线程的最终解决方案:
// no mocking of the whole module
const abcjs= require('abc');
describe("1st test", () => {
test("should return true", async () => {
// Try using jest.spyOn() instead of jest.fn
jest.spyOn(abcjs.a,'b').mockImplementationOnce(() => Promise.resolve(true)));
//expect statement here
});
});
describe("2nd test", () => {
jest.restoreAllMocks(); // <----------- remember to add this
test("should return false", async () => {
jest.spyOn(abcjs.a,'b').mockImplementationOnce(() => Promise.resolve(false)));
// expect statement here
});
});
基本上,不要模拟整个模块,而只模拟你想要的功能。
推荐阅读
- eclipse-rcp - NatTable 1.6 - TreeLayer - 展开/折叠三角形在折叠上面的一行后不跟随它们的行
- azure - DurableOrchestrationClient.CreateCheckStatusResponse 上的自定义域
- sql - SQL Server通过查询父节点属性名返回子节点(值)
- php - php没有将数据插入mysql数据库
- firebase - Firestore 补丁映射值 REST API
- git - Git浅克隆:只有最近X个月有活动的分支
- r - 计算每组中的观察次数
- php - jquery ajax 值到 php 变量
- json - 从 Java Swagger 模型创建 Json
- accessibility - 什么是正确的屏幕阅读器可访问标记