javascriptjasminejasmine-node

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"


Solution

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