Mocking dependent modules using Jasmine

158 Views Asked by At

I have a Javascript modular application not using Angular/Backbone. I am trying to write test case for my startup module but facing issue.

Startup.js:

    window.claimStartup = function (options) {
    this.options = $.extend({}, this.options, options);
    this.cmds = new this.serviceModule(this);
    }

     getClaimsCategories: function (claimTypeCode) {
        var self = this;
        // Refresh claim categories
        return $.when(self.cmds.getClaimsCategories(claimTypeCode))
            .then(function (response) {
                return response;
            });
    }, 

Service.js:

    claimStartup.prototype.serviceModule = function (cfg) {   
    this.cfg = cfg;
    this.init();
    }

StartUp.spec.js:

var claimStartUp;

beforeEach(function () {
spyOn(window.claimStartup.prototype, 'serviceModule');
  claimStartUp = new window.claimStartup();

});

it("should be able to get categories", function () {
jasmine.spyOn(claimStartUp.cmds, 'getClaimsCategories').andReturn('XYZ');
var categories=  claimStartup.getClaimsCategories('ABC');
expect(categories).toEqual('XYZ');
});

I am getting error when populating this.cmds it says serviceModule constructor not defined, actually I need to mock serviceModule when claimStartup is initialised.

Please let me know how can i write test case in this scenario.

1

There are 1 best solutions below

0
On

I am able to fix this, this might be useful for others.

      var claimStartUp;

      beforeEach(function () {
      var spyService = jasmine.createSpy('serviceModule');
      var methodService = window.claimStartup.prototype.serviceModule;
      window.claimStartup.prototype.serviceModule = spyService;

      var spyUI = jasmine.createSpy('uiModule');
      var methodUI = window.claimStartup.prototype.uiModule;
      window.claimStartup.prototype.uiModule = spyUI;

      claimStartUp = new window.claimStartup();

  });