Search code examples
javascriptecmascript-6sinon

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.


Solution

  • 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'