How to spy a function without root object

4,740 views
Skip to first unread message

Hoàng Ngọc Dũng

unread,
Nov 10, 2015, 11:37:22 PM11/10/15
to Jasmine
Hi friends
I got a case

import velocity from 'velocity-animate';

export function slideDown(element, callback) {
velocity(element, 'slideDown', {
duration: 250,
complete: callback
});
}


spyOn('velocity');

I can't spy a single function in this case. Please help me !

Gregg Van Hove

unread,
Nov 11, 2015, 12:11:47 AM11/11/15
to jasmi...@googlegroups.com
In a browser type environment you would probably do something like:

`spyOn(window, 'velocity')`

because that's where any global functions would actually be living. In a CommonJS environment, you should be able to use `global` instead of `window` to accomplish the same thing.

Hope this helps. Thanks for using jasmine!

-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.

Hoàng Ngọc Dũng

unread,
Nov 11, 2015, 2:05:12 AM11/11/15
to Jasmine
Sorry and how about for the case we have our own function from our module, and it is not attached with global/window.

- utils.js

export function getProducts
() {};
export function getCategories() {};

- stores.js

import {
getProducts} from './utils';

export default {
   trick() {
      let total =
getProducts();

      if (total) { //do something}
      else {} { // do something}
   }
};

- stores-test.js

import {
getProducts } from './utils';
import
stores from './stores';

it('Should Test', () => {
   spyOn(getProducts).and.returnValue('5');
});

Gregg Van Hove

unread,
Nov 30, 2015, 3:10:30 PM11/30/15
to jasmi...@googlegroups.com
The `spyOn` function works by replacing the original function on the owning object with a Spy object. So if there is no owner object, you can't use `spyOn`. You could look into using `jasmine.createSpy` to get a raw Spy object back, but since jasmine won't know what you're doing with it, it is unable to clean up the way that `spyOn` does.

Hope this helps.

-Gregg
Reply all
Reply to author
Forward
0 new messages