简体   繁体   English

带有 sinon 的 Stub es6 getter setter

[英]Stub es6 getter setter with sinon

If you use the following es6 syntax for getters/setter如果您对 getter/setter 使用以下 es6 语法

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

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

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

How would you stub the getter method?你将如何存根 getter 方法?

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

Does not seem to be working.似乎没有工作。

Github issue led me to: sinon js doc Github 问题导致我: sinon js doc

stub.get(getterFn)

Replaces a new getter for this stub.替换此存根的新吸气剂。

var myObj = {
    prop: 'foo'
};

sinon.stub(myObj, 'prop').get(function getterFn() {
    return 'bar';
});

myObj.prop; // 'bar'

stub.set(setterFn)

Defines a new setter for this stub.为此存根定义一个新的设置器。

var myObj = {
    example: 'oldValue',
    prop: 'foo'
};

sinon.stub(myObj, 'prop').set(function setterFn(val) {
    myObj.example = val;
});

myObj.prop = 'baz';

myObj.example; // 'baz'

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

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