简体   繁体   English

如何在 Chai 中模拟或存根 'instanceof' | 诗浓 | 摩卡

[英]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.基本上我必须为内部逻辑编写一些测试用例,但问题首先是我无法通过的 if 语句。 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

You can use Object.create() to create blank(-ish) objects with a given prototype that will pass an instanceof check:您可以使用Object.create()创建具有给定原型的空白(-ish)对象,该原型将通过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

Beware that this object will still inherit properties from its prototype, ie the calculate() method above.请注意,该对象仍将继承其原型的属性,即上面的calculate()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM