Search code examples
javascriptsinon

Sinon: calling a method from the child object but spying the one from the grand parent class only


Having in javascript

class GrandParent {
  myfunc() {
    console.log('Parent myfunc');
  }
}


class Parent extends GrandParent {
  myfunc() {
    // do something else here
    for (let i = 0; i < 3; i++) {
      super.myfunc()
    }
  }
}

class Child extends Parent {
  mymeth() {
    // do something here
      this.myfunc();
    }
}

let spy = sinon.spy(Child.<?>, "myfunc")

let child = new Child();
child.myfunc();

console.log(spy.callCounts); --> 3 expected

I have only access to Child class (through a require which exports only this class, this must not be changed) and I would like to spy the myfunc() method from GrandParent class in order to get spy.callCounts === 3 finally.

Is it possible to do and how?

Thanks in advance


Solution

  • You need to stub on GrandParent.prototype.

    Also, for safety reasons, it's better to first install spies/stubs, then create objects:

    If it's not accessible by imports, you can use reflection (in this case "twice":

    const parentConstructor = Reflect.getPrototypeOf(Child)
    const grandpaConstructor = Reflect.getPrototypeOf(parentConstructor);
    
    let spy = sinon.spy(grandpaConstructor.prototype, "myfunc")
    let child = new Child();
    child.myfunc();