简体   繁体   中英

Spying on global object using jasmine

Here is my js code

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

And here is how i am trying to create a spy and writing my spec for the above functon.

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)

    });

});

The first expect is passing without any errors where as the second expect is giving me an error "plan.apply is not a function"

You haven't actually attached the function add() to MyObjectFactory . Try something like this:

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);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM