javascript - 承诺后需要帮助测试 then 部分
问题描述
我正在尝试对我的节点应用程序进行单元测试,并且在我正在测试的方法中做出承诺之后,我在测试 then 部分时遇到了挑战。
// toBeTested.js
const { fun1 } = require("./somejs");
const { fun2 } = require("./someotherjs");
const { fun3 } = require("./anotherjs");
exports.somefunction = ({ p1, p2, p3, p4 }) => {
fun1(p1, p2)// fun1() returns a promise
.then(
results => {
fun2(fun3(results), p3, p4);
}
)
}
这是测试文件,由于某种原因,fun2 和 fun3 似乎没有被调用。
// toBeTested.test.js
const { somefunction } = require("./toBeTested.js");
const { fun1 } = require("./somejs");
const { fun2 } = require("./someotherjs");
const { fun3 } = require("./anotherjs");
jest.mock("./somejs.js", () => {
return {
fun1: jest.fn((p1, p2) => {
return Promise.resolve(() => {
});
})
}
});
jest.mock("./someotherjs.js", () => {
return {
fun2: jest.fn((p1, p2, p3) => { })
}
});
jest.mock("./anotherjs.js", () => {
return {
fun3: jest.fn((p1) => {
return [];
})
};
});
const mockObj = {
p1: "p1",
p2: "p2",
p3: "p3",
p4: "p4"
};
afterEach(() => {
jest.resetAllMocks();
jest.restoreAllMocks();
});
describe("Test toBeTested.js", () => {
it("somefunction() - success", () => {
somefunction(mockObj);
expect(fun1).toHaveBeenCalled();
expect(fun1).toHaveBeenCalledWith(mockObj.p1, mockObj.p2);
expect(fun3).toHaveBeenCalled(); // Fails here
expect(fun2).toHaveBeenCalled(); // Fails here too
});
})
谢谢你。
PS:说到 jest 和 node js 开发,我还是个初学者。
解决方案
问题是fun3
并且fun2
被异步调用。解决后您应该等待它们fun1
:
describe("Test toBeTested.js", () => {
it("somefunction() - success", async () => {
somefunction(mockObj);
expect(fun1).toHaveBeenCalledWith(mockObj.p1, mockObj.p2);
await expect(fun1.mock.results[0]).resolves;
expect(fun3).toHaveBeenCalled();
expect(fun2).toHaveBeenCalled();
});
})
参考
推荐阅读
- css - ionic 4 ion-item 按列而不是按行显示项目
- java - XML 外部实体引用的不当限制(CWE ID 611)(6 个缺陷)
- excel - 错误 424:需要对象 _ 将表设置为范围
- android - InApp 购买 - 到期和开始日期详细信息
- android - OrderByChild() 没有对我的 firebase 数据进行排序
- javascript - 如何通过关键字获得最相关的问题
- python - 如何使用python删除谷歌存储文件夹中的所有文件
- azure - 多租户 - Azure IoT 客户是否应该共享一个中心?
- pandas - Pandas 删除重复项(也是逆序)(Python 3.7)
- ansible - 无法检查保险库状态,获取错误检查密封状态