Jasmine spyOn - method does not exist in jQuery anonymous function

2,508 views
Skip to first unread message

Ben Grunfeld

unread,
Jul 14, 2014, 11:12:17 PM7/14/14
to jasmi...@googlegroups.com

Have searched for the answer to this problem on SO and other forums. Didn't find solution.

I'm running into a problem where Jasmine cannot find a function inside of a jQuery code block, whether the Jasmine code is inside the jQuery function or not.

$(function() {
    function foo(param1, param2) {
        // some code
    }

    describe("Foo function", function () {

        spyOn(window, 'foo');

        foo(1, 2);

        it("Should be found by Jasmine", function(){
            expect(window.foo).toHaveBeenCalled();
        });
    });
});

Error: foo() method does not exist

I have also tried spyOn($, 'foo')spyOn($.fn, 'foo') and others.

Also, the following code does not work either.

$(function() {
    function foo(param1, param2) {
        // some code
    }
});

describe("Foo function", function () {

    spyOn(window, 'foo');

    foo(1, 2);

    it("Should be found by Jasmine", function(){
        expect(window.foo).toHaveBeenCalled();
    });
});

So how would one make both of these code blocks work (i.e. where the Jasmine code is inside of the jQuery function, and where it is outside of the jQuery function)?

Gregg Van Hove

unread,
Jul 15, 2014, 4:05:24 PM7/15/14
to jasmi...@googlegroups.com
Your `foo` function is not actually on the `window` object, but a closed over function local to the `$()` call. This is why you can't use `spyOn(window, 'foo')`.


-Gregg


--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to jasmine-js+...@googlegroups.com.
To post to this group, send email to jasmi...@googlegroups.com.
Visit this group at http://groups.google.com/group/jasmine-js.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages