简体   繁体   中英

Stub es6 getter setter with sinon

If you use the following es6 syntax for getters/setter

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?

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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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