Search code examples
javascriptnode.jsjasmine-nodespy

Jasmine-node - Creating a spy on a constructor called inside other function


I'm novice in jasmine and I need to write some unit tests for node.js app in this framework. I have some problems, one of them is this described below:

var sampleFunction = function(){
    var loader = new Loader(params);
    // rest of logic here
}

I want to write unit test for sampleFunction. To do this I need to create spy on Loader constructor and check what this constructor gets as params and what kind of object is it returning.

Any ideas how to do that? I tried to create spy on Loader.prototype.constructor but it wasn't a solution to this problem.


Solution

  • OK, so normally in client-side JavaScript you would use the window object like so jasmine.spyOn(window, 'Loader')

    In node, however, there is no window object and despite claims to the contrary global is not a substitute (unless you are in the REPL which runs in global scope).

    function MyConstructor () {}
    console.log(global.MyConstructor); --> undefined
    console.log(this.MyConstructor); --> undefined
    

    So, in node you need to attach your constructor to an object. So just do something like this

    var Helpers = {
       Loader: Loader
    };
    
    var constSpy = jasmine.spyOn(Helpers, 'Loader').andCallThrough();
    
    sampleFunction();
    
    expect(constSpy).toHaveBeenCalled();
    

    The andCallThrough call is only necessary if you want your constructor to do something (often with constructor you do).

    This is a little hacky, but it works and seems to be the only way to achieve this through jasmine's implementation within node.