'How to mock or stub 'instanceof' in Chai | Sinon | Mocha

I have a condition where i need to mock or stub data.

    var array =['add','divide']
    var add =listMehtod[0];
    if(add instanceof Calculator){  // how to test this ?
       // some logic
     }

basically i have to write some test case for inside logic, but the problem is first if statement which i am not able to pass through. is there a any way to handle it by chai or sinon ?

test case :

  var a = new Calculator();
  expect(a).to.be.instanceOf(Calculator) // this is returning false


Solution 1:[1]

You can use Object.create() to create blank(-ish) objects with a given prototype that will pass an instanceof check:

class Calculator {
    constructor() { this._calculator = 'CALCULATOR' }
    calculate(a, b) { return a + b }
}
const calc = Object.create(Calculator.prototype)
console.log(calc instanceof Calculator) // => true

Beware that this object will still inherit properties from its prototype, i.e. the calculate() method above.

Solution 2:[2]

If you have access to the object being used on the right side of instanceof, you can override its Symbol.hasInstance property:

class Foo {}
const mockFooInstance = {}

Object.defineProperty(Foo, Symbol.hasInstance, {
    value: instance => {
        return instance === mockFooInstance;
    },
});

console.log(mockFooInstance instanceof Foo); // true

Note that this breaks instanceof for the real Foo though:

const realFoo = new Foo();
console.log(realFoo instanceof Foo); // false

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 millimoose
Solution 2 Jespertheend