4

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
jjmerelo
  • 22,578
  • 8
  • 40
  • 86
jsduniya
  • 2,464
  • 7
  • 30
  • 45

2 Answers2

5

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.

millimoose
  • 39,073
  • 9
  • 82
  • 134
1

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
Jespertheend
  • 1,814
  • 19
  • 27