使用Sinon框架模拟ES6中的getter和setter方法

4
如果您使用以下 ES6 语法来定义 getter/setter:
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')

似乎没有起作用。

1个回答

8

Github问题引导我到:sinon js文档

stub.get(getterFn)

为该存根设置新的获取器。

var myObj = {
    prop: 'foo'
};

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

myObj.prop; // 'bar'

stub.set(setterFn)

为该桩对象定义一个新的setter函数。

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

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

myObj.prop = 'baz';

myObj.example; // 'baz'

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