netmajor
netmajor

Reputation: 6585

Test that function is executed in ES6 constructor using Jasmine

I have created a simple example on JSFiddle to test a problem I encountered in my project:

describe('testing es6 and jasmine', function() {
  describe('let', () => {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
    it('is es6 works', function() {
      class Test {
        constructor() {
          var x = this.sum(1, 1);
        }
        sum(a, b) {
          return a + b;
        }
      }
      var test = new Test();
      spyOn(test, 'sum').and.callThrough();
      expect(test.sum).toBeDefined();
      expect(test.constructor).toBeDefined();
      expect(test.sum).toHaveBeenCalled();
    });

  });
});

Problem is that I execute a method in the constructor and I want to check if it was executed. Why in my example does Jasmine tell that it is not ?

Upvotes: 3

Views: 939

Answers (1)

robertklep
robertklep

Reputation: 203439

The issue is that you call the constructor (by using new Test) before you install the spy. So the function has already been called by the time it gets spied on.

To solve this, you can spy on Test.prototype.sum, before calling the constructor:

spyOn(Test.prototype, 'sum').and.callThrough();
var test = new Test();

See the updated fiddle.

Upvotes: 6

Related Questions