1

We're using require and Browserify, so single-function modules are imported like this:

var loadJson = require('../loadJson');

and used like this:

x = loadJson(url);

I'd like to spyOn that loadJson function, but it doesn't seem to be possible.

It's not a global function, so this doesn't work:

spyOn(window, 'loadJson')

It's not a local function, so this doesn't work:

loadJson = createSpy('loadJsonSpy', loadJson).and.callThrough();

When I require the module into my Jasmine spec, the function is visible inside that closure, but that's not the same closure as the other module which are actually using loadJson for real.

So in short, I think it's not possibly to use spyOn in this case - is that correct? Any creative workarounds?

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
  • Oh. http://philipwalton.com/articles/how-to-unit-test-private-functions-in-javascript/ – Steve Bennett Jan 06 '16 at 04:06
  • That link is for testing private functions. ```loadJson``` is not a private function in your case. – Anand S Jan 06 '16 at 18:28
  • Are you sure? It's specifically about testing functions within closures - it just calls them "private functions". – Steve Bennett Jan 07 '16 at 00:47
  • ```function closureOne(){function privA(){} return function pubB(){}} function closureTwo(){var refOfB = closureOne()}``` In this example ```privA()``` is private. ```pubB()``` is public. In ```cloureTwo()```, by referencing ```pubB``` to ```refOfB```(a closure private variable) does not make ```pubB``` a private function. – Anand S Jan 07 '16 at 17:56
  • ```pubB``` is similar to ```loadJson``` in you case. – Anand S Jan 07 '16 at 17:59
  • Did my answer work? How did you solve this?? – Anand S Jan 08 '16 at 08:19

1 Answers1

0

If loadJson is singleton, then you can do this.

var functionsToSpyOn = {loadJson: loadJson}
spyOn(functionsToSpyOn, 'loadJson')

This is the workaround I used when I had the same problem.

Anand S
  • 1,068
  • 9
  • 22