Mocking a global function

6,975 views
Skip to first unread message

Blake VandeMerwe

unread,
Jun 5, 2012, 1:39:02 PM6/5/12
to Jasmine
How do I mock (spy) a function in the global space?

For example, I have in common.js:

isPending() { ... }

...and I need this mocked to return True when a second function is
being tested. How is this done since it doesn't follow the prototype
convention? This is being tested with jasmine, jasmine adapter, and
jstestdriver.

Thanks in advance.

Derick Bailey

unread,
Jun 5, 2012, 9:21:07 PM6/5/12
to jasmi...@googlegroups.com
you need a reference to the global object. if you're doing in-browser testing, it's "window"

spyOn(windows, "globalFunction");


otherwise, a simple function to retrieve it can be useful:

var global = (function(){ return this; })();

spyOn(global, "globalFunction");

--
You received this message because you are subscribed to the Google Groups "Jasmine" group.
To post to this group, send email to jasmi...@googlegroups.com.
To unsubscribe from this group, send email to jasmine-js+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/jasmine-js?hl=en.

Ben Loveridge

unread,
Jun 5, 2012, 9:52:04 PM6/5/12
to jasmi...@googlegroups.com
Note that Jasmine also has a function that will give you the global object. 

jasmine.getGlobal()
-- 
Ben Loveridge 

Derick Bailey

unread,
Jun 5, 2012, 10:23:58 PM6/5/12
to jasmi...@googlegroups.com
oh nice - didn't know that.

-- Derick

Austin Vance

unread,
Jun 5, 2012, 6:39:13 PM6/5/12
to jasmi...@googlegroups.com
spyOn(window, 'isPending');

Should do the trick.

- Austin
Reply all
Reply to author
Forward
0 new messages