How to spyOn a global function and return a value in Jasmine
Asked Answered
P

1

6

How can I spy on MyFunction and return 2 in Jasmine 2.0?

I have the following code that errors on the first line inside shouldPass with:

Error: function MyFunction(){ return 1; }() method does not exist

It appears to be using the entire function as the function name

MyFile.js:

MyFunctionToTest = function(){
    return MyFunction() + 1;
}

function MyFunction(){ return 1; }

MyFileSpec.js:

describe("myTest", function(){
    it("shouldPass", function(){
        spyOn("MyFile", MyFunction).and.returnValue(2);

        expect(MyFunctionToTest()).toEqual(3)
    })
})
Pyrology answered 26/5, 2017 at 14:42 Comment(0)
M
5

You are trying to spy on an anonymous/global function. You can probably just redefine it with a spy.

MyFunction = jasmine.createSpy().and.returnValue(2);
Molecular answered 26/5, 2017 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.