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

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

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