yoogeeks yoogeeks - 19 days ago 11
Node.js Question

Jasmine : Spying on a function call of another module

I have the following code structure :

const finalCall = require('./final.js');
function Func(){
this.process = {
initCall: function(params, callback){
let proParams;
//processing...
return finalCall(proParams, callback);
}
}
}


Now I need to test if my
initCall
function correctly processes the
params
and makes call to
finalCall
. I need to know how do I create a spy on my
finalCall
function, so when it gets called, I can track the
proParams
.
I have tried something like :

const func = new Func();
let proParams = null;
spyOn(func.process.initCall, "finalCall").and.callFake(function(pParams, callback){
proParams = pParams;
});
let params = { };
func.process.initCall(params, null);
expect(func.process.initCall.finalCall).toHaveBeenCalled();
expect(proParams).toEqual('...');


I am missing on what object I can access finalCall, or if there is another way to do so. Thanks in advance.

Answer

Finally I found a workaround to my problem. I created a prototype of the function finalCall() in my constructor Const, and put a spyOn on its object.

Solution

Main module:

const finalCall = require('./final.js');
function Func(){
  const self = this;
  this.process = {
    initCall: function(params, callback){
      let proParams;
      //processing...
      return self.finalCall(proParams, callback);
    }
  }
}
Func.prototype = finalCall;

and in my Spec file:

const func = new Func();
let proParams = null;
spyOn(const, finalCall);
let params = { };
func.process.initCall(params, null);
expect(func.finalCall).toHaveBeenCalled();