lundi 31 août 2015

Jasmine: testing method called from window scope function

I'm using Jasmine to te test some of my code. It looks a bit like this

# main logic
function Analytics() {
  this.construct = function() {
  }

  this.foo = function() {
  }

  this.bar = function() {
  }
}

# "main" routine, called by jQuery on ready, or direct by Jasmine
function analytics() {
  new Analytics().construct();
}

# calls main routine
$(document).ready(function () {
  analytics();
});

When running this in the browser, it works fine. However, when I want to test my code with Jasmine (test if the constructor gets called when calling analytics() it fails.

Expected spy construct to have been called. (1)

This is what the spec looks like:

it('should call the constructor when the document is ready', function({
    var _analytics = new Analytics();
    spyOn(_analytics, 'construct')
    analytics();  # note this is the "main" routine
    expect(_analytics.construct).toHaveBeenCalled();
})

My testcase seems to be incorrect but I don't really see how. Does anyone have an explanation for this behavior?

Aucun commentaire:

Enregistrer un commentaire