Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 609
netmajor Avatar asked May 04 '26 17:05

netmajor


1 Answers

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.

like image 88
robertklep Avatar answered May 06 '26 08:05

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!