Using Jasmine to spy on a function without an object

Chetter Hummin picture Chetter Hummin · Mar 1, 2012 · Viewed 110.7k times · Source

I'm new to Jasmine and have just started using it. I have a library js file with lots of functions which are not associated with any object (i.e. are global). How do I go about spying on these functions?

I tried using window/document as the object, but the spy did not work even though the function was called. I also tried wrapping it in a fake object as follows :

var fakeElement = {};
fakeElement.fakeMethod = myFunctionName;
spyOn(fakeElement, "fakeMethod");

and test with

expect(fakeElement.fakeMethod).toHaveBeenCalled();

This does not work either as the spy did not work

Answer

ndp picture ndp · Mar 1, 2012

If you are defining your function:

function test() {};

Then, this is equivalent to:

window.test = function() {}  /* (in the browser) */

So spyOn(window, 'test') should work.

If that is not, you should also be able to:

test = jasmine.createSpy();

If none of those are working, something else is going on with your setup.

I don't think your fakeElement technique works because of what is going on behind the scenes. The original globalMethod still points to the same code. What spying does is proxy it, but only in the context of an object. If you can get your test code to call through the fakeElement it would work, but then you'd be able to give up global fns.