Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!