Jasmine spyOn - method does not exist in jQuery anonymous function

痞子三分冷 提交于 2019-12-06 02:36:04

I hate to answer my own question, but I rather that than other people not learning from my mistakes.

There are 2 issues here:

  1. Jasmine needs a containing object
  2. You cannot access functions/variable outside the scope of a JS function

1 - Jasmine spies need to use a containing object, and if one can't be found, you just need to make it yourself. So the following code works:

// Using Jasmine inside of a jQuery anon function
$(function () {

    function foo() {
        // Some code
    }

    describe("Foo function", function () {

        it("Should be findable by Jasmine", function () {
            var Thing = {}
            Thing.foo = foo;
            spyOn(Thing, 'foo');
            Thing.foo(2)
            expect(Thing.foo).toHaveBeenCalled();
        });
    });
});

2 - If you have the describe block outside of the jQuery anon function, it won't be able to access any values from within the jQuery block, hence the second code example above won't work, no matter what you do.

Not sure why would you need spies for "private" functions. You can do the following Demo.

$(function(){
    function foo() {
        return 'foo';
    };

    function baz() {
        return foo();    
    }

    describe('foo', function() { 
        //create a spy and define it to change foo
        foo = jasmine.createSpy().andCallFake(foo);


        it('should be a function', function() {
            expect(typeof foo).toBe('function');             
        });        

        var result = baz(); //call function you want to test

        it('should be called', function() {            
            expect(foo).toHaveBeenCalled(); //check if foo was called by baz   
        });        

        //additional check for return since .andCallThrough won't work
        it('should return foo', function() { 
            expect(result).toBe('foo');    
        })

    });
});

It looks like you just need to set up your jQuery function differently. Try...

(function ($) {
    $.fn.foo = function (param1, param2) {
        // some code
    };
}(jQuery));

and then your Jasmine script will look like...

describe("Foo function", function () {

    var test = spyOn($.fn, 'foo');

    $.fn.foo(1,2);

    it("Should be found by Jasmine", function(){
        expect(test).toHaveBeenCalled();
        expect(test).toHaveBeenCalledWith(1,2);
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!