使用茉莉花监视全局对象

Spying on global object using jasmine

这是我的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 is not a function"

您实际上并未将函数 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);
    });
});