Saturday, May 11, 2024
102
rated 0 times [  107] [ 5]  / answers: 1 / hits: 149101  / 12 Years ago, thu, march 1, 2012, 12:00:00

I'm using Jasmine and 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.


More From » unit-testing

 Answers
58

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.


[#87126] Wednesday, February 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adrienkeithr

Total Points: 503
Total Questions: 126
Total Answers: 110

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;