Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
Testing instances in a function that depends on instanceof (JEST)

I am running into an issue while writing unit test to test a function that has instance check. Business logic:

let status = new B();
const testFunction = () => {
    if (status instanceof A) {
      console.log('inside A')
    } else if (status instanceof B) {
      console.log('inside B')
    } else {
      console.log('No matchers')
    }

}

Unit Test:

describe('test', ()=>{
  
  it("should test b", ()=>{
    let status = new A()
    expect(status).toBeInstanceOf(A) // passes
    expect(logSpy).toHaveBeenCalledWith('inside A') // fails and it expects 'inside B'
  })
})

One reason I feel the test is failing is because in the original file, status is return an instance of class B, so it matches else if and not if. I am not sure how to test this code without change status? Is there a way that I am missing out?

EDIT: Here the assumption is that the testFunction() is already invoked in unit tests

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can pass the status as parameter of your function;

const testFunction = (status) => {
  if (status instanceof A) {
    console.log('inside A')
  } else if (status instanceof B) {
    console.log('inside B')
  } else {
    console.log('No matchers')
  }
}

Then testFunction() should be called with the status that you need to test;

const status = new A();
testFunction(status);

The problem with your test is that the function that your are testing has its own scope, the other solution is to mock the variable, but could be most confused

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda