存根 es6 getter setter 与 sinon
Stub es6 getter setter with sinon
如果对 getters/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')
似乎没有用。
Github issue led me to : 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)
为此存根定义一个新的 setter。
var myObj = {
example: 'oldValue',
prop: 'foo'
};
sinon.stub(myObj, 'prop').set(function setterFn(val) {
myObj.example = val;
});
myObj.prop = 'baz';
myObj.example; // 'baz'
如果对 getters/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')
似乎没有用。
Github issue led me to : 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)
为此存根定义一个新的 setter。
var myObj = {
example: 'oldValue',
prop: 'foo'
};
sinon.stub(myObj, 'prop').set(function setterFn(val) {
myObj.example = val;
});
myObj.prop = 'baz';
myObj.example; // 'baz'