首页 > 解决方案 > 承诺后需要帮助测试 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 开发,我还是个初学者。

标签: javascriptnode.jsunit-testingjestjs

解决方案


问题是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();
   });
})

参考


推荐阅读