最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to spyOn a global function and return a value in Jasmine - Stack Overflow

programmeradmin2浏览0评论

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

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)
    })
})
Share Improve this question edited May 4, 2022 at 10:40 Seth Flowers 9,2102 gold badges33 silver badges44 bronze badges asked May 26, 2017 at 14:42 tallpaultallpaul 1,5132 gold badges15 silver badges38 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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);
发布评论

评论列表(0)

  1. 暂无评论