0

I'm trying to test a function call in the next scenario:

JS:

var Demo = function(option) {
  if (option) func();

  function func() {
    console.log('called')
  }

  return {
    'func': func
  }
}

Jasmine:

beforeEach(function() {
  var demo = new Demo(true);
  spyOn(demo, 'func');

  this.demo = demo;
});

it("should call func()", function() {
  expect(this.demo.func).toHaveBeenCalled();
});

Despite it logs 'called' in the console it fails the spec with:

Expected spy func to have been called.

From the code flow I suppose it happens because the spying begins after the function was called. So my question - what is the proper way to capture the function call in the test?

JSFiddle

Zoltan Toth
  • 46,981
  • 12
  • 120
  • 134

1 Answers1

1

This may be a better way to do this. Add func as part of the Demo prototype. then you can hook up the spy to the prototype.

var Demo = function(option) {
  if (option) this.func();
}

Demo.prototype.func = function(){
    console.log("called")
}

beforeEach(function() {
    spyOn(Demo.prototype, 'func')
  var demo = new Demo(true);
  this.demo = demo;
});

it("should call func()", function() {
  expect(this.demo.func).toHaveBeenCalled();
});

http://jsfiddle.net/kfu7fok1/6/

ThrowsException
  • 2,586
  • 20
  • 37
  • Thank you. I've seen [this answer](http://stackoverflow.com/a/17920698/7631470) - just was wondering if there is another way to achieve this. – Zoltan Toth Mar 01 '17 at 21:13
  • Yea as you pointed out the function has already been called by the time you hook up the spy in your original question. Doing it with the prototype does have performance benefits. In your original question every time you make a new Demo object you get a new instance of `func`. with Demo.prototype.func all instances share this through the prototype. – ThrowsException Mar 01 '17 at 22:25