这是我的js代码

launchTask(taskId)
{
    const taskIds = window.external.MyObjectFactory("INDEXED");
    taskIds.add(taskId);
}


这就是我试图创建间谍并为上述功能编写规格的方式。

describe("The launchTask function", () => {
    beforeEach(() => {
        global.external.MyObjectFactory= jasmine.any(Function);
        spyOn(global.external, 'MyObjectFactory').and.callThrough();
        jasmine.createSpyObj("global.external.MyObjectFactory", ["add"]);
    });
    it("Scene 1", () => {
        launchTask(123);
        expect(global.external.MyObjectFactory).toHaveBeenCalledWith("INDEXED")
        expect(global.external.MyObjectFactory("INDEXED").add).toHaveBeenCalledWith(123)

    });

});


第一个期望通过且没有任何错误,而第二个期望给了我一个错误“ plan.apply不是函数”

最佳答案

您实际上并没有将功能add()附加到MyObjectFactory。尝试这样的事情:

describe("The launchTask function", () => {
    let spyObj;
    beforeEach(() => {
        global.external.MyObjectFactory= jasmine.any(Function);
        spyObj = jasmine.createSpyObj(["add"]);
        spyOn(global.external, 'MyObjectFactory').and.returnValue(spyObj);
    });
    it("Scene 1", () => {
        launchTask(123);
        expect(global.external.MyObjectFactory).toHaveBeenCalledWith("INDEXED");
        expect(spyObj.add).toHaveBeenCalledWith(123);
    });
});

09-19 11:12