[英]Need help testing the then part after a promise
I'm trying to unit test my node application and I am having challenges testing the then part after a promise inside the method I'm testing.我正在尝试对我的节点应用程序进行单元测试,并且在我正在测试的方法中测试 promise 之后的 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);
}
)
}
Here's the test file, the fun2 and fun3 doesn't seem to be getting called for some reason.这是测试文件,由于某种原因,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
});
})
Thank you.谢谢你。
PS: I'm still a beginner when it comes to jest and node js development. PS:说到 jest 和 node js 开发,我还是个初学者。
The problem is that fun3
and fun2
are called asynchronously.问题是fun3
和fun2
是异步调用的。 You should wait to expect them after fun1
resolves:在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();
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.