Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

133
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda