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

141
Views
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 answers
Answer question

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