如何在Chai | Sinon | Mocha中模拟或替换'instanceof'?

4

我有一个需要模拟或存根数据的情况。

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

基本上我需要为内部逻辑编写一些测试用例,但问题是我无法通过第一个if语句。是否有任何使用chai或sinon来处理它的方法?

测试用例:

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

5
您可以使用Object.create()创建具有特定原型的空白对象,该对象将通过instanceof检查:
class Calculator {
    constructor() { this._calculator = 'CALCULATOR' }
    calculate(a, b) { return a + b }
}
const calc = Object.create(Calculator.prototype)
console.log(calc instanceof Calculator) // => true

请注意,该对象仍将继承其原型的属性,即上面的calculate()方法。


1

如果您可以访问右侧使用的对象,则可以覆盖其Symbol.hasInstance属性:

class Foo {}
const mockFooInstance = {}

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

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

请注意,这会破坏真实的Fooinstanceof
const realFoo = new Foo();
console.log(realFoo instanceof Foo); // false

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接