'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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 BlackSlash