【问题标题】:Stub es6 getter setter with sinon带有 sinon 的 Stub es6 getter setter
【发布时间】:2020-03-17 09:52:03
【问题描述】:

如果你对 getter/setter 使用下面的 es6 语法

class Person {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name.toUpperCase();
  }

  set name(newName) {
    this._name = newName;
  } 
}

你将如何存根 getter 方法?

const john = new Person('john')
sinon.createSandbox().stub(john, 'name').returns('whatever')

似乎没有工作。

【问题讨论】:

    标签: javascript ecmascript-6 sinon


    【解决方案1】:

    Github issue 引导我到:sinon js doc

    stub.get(getterFn)

    为这个存根替换一个新的 getter。

    var myObj = {
        prop: 'foo'
    };
    
    sinon.stub(myObj, 'prop').get(function getterFn() {
        return 'bar';
    });
    
    myObj.prop; // 'bar'
    

    stub.set(setterFn)

    为此存根定义一个新的设置器。

    var myObj = {
        example: 'oldValue',
        prop: 'foo'
    };
    
    sinon.stub(myObj, 'prop').set(function setterFn(val) {
        myObj.example = val;
    });
    
    myObj.prop = 'baz';
    
    myObj.example; // 'baz'
    

    【讨论】:

      猜你喜欢
      • 2016-07-01
      • 1970-01-01
      • 2016-02-22
      • 2021-02-23
      • 1970-01-01
      • 2016-05-22
      • 1970-01-01
      • 2016-11-09
      • 2017-05-21
      相关资源
      最近更新 更多