【问题标题】:Sinon: calling a method from the child object but spying the one from the grand parent class onlySinon:从子对象调用方法,但仅从父类中监视方法
【发布时间】:2021-11-11 12:44:59
【问题描述】:

在javascript中拥有

class GrandParent {
  myfunc() {
    console.log('Parent myfunc');
  }
}


class Parent extends GrandParent {
  myfunc() {
    // do something else here
    for (let i = 0; i < 3; i++) {
      super.myfunc()
    }
  }
}

class Child extends Parent {
  mymeth() {
    // do something here
      this.myfunc();
    }
}

let spy = sinon.spy(Child.<?>, "myfunc")

let child = new Child();
child.myfunc();

console.log(spy.callCounts); --> 3 expected

我只能访问 Child 类(通过仅导出此类的要求,不得更改)并且我想从 GrandParent 类中监视 myfunc() 方法以获取 spy.callCounts === 3 最后。

有没有可能,怎么做?

提前致谢

【问题讨论】:

    标签: javascript sinon


    【解决方案1】:

    你需要存根GrandParent.prototype

    另外,为了安全起见,最好安装间谍/存根,然后创建对象:

    如果无法通过导入访问,您可以使用反射(在本例中为“两次”:

    const parentConstructor = Reflect.getPrototypeOf(Child)
    const grandpaConstructor = Reflect.getPrototypeOf(parentConstructor);
    
    let spy = sinon.spy(grandpaConstructor.prototype, "myfunc")
    let child = new Child();
    child.myfunc();
    

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 2011-04-17
      • 2017-11-09
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2015-10-11
      • 2014-06-11
      相关资源
      最近更新 更多