Sinon: Document how to stub getters and setters

Created on 12 Jul 2016  路  8Comments  路  Source: sinonjs/sinon

PR #692 introduced the feature of stubbing getters and setters. This is as of yet undocumented. Some of the comments show examples of how to make use of this feature.

Easy Documentation Help wanted

Most helpful comment

If you're reading this from a google search you want to read https://sinonjs.org/releases/latest/stubs/ instead!

All 8 comments

@fatso83 do you think that #1182 adequately solved this issue? Can we close it?

With the introduction of callsFake, the documented way of stubbing getters/setters logs a warning:

sinon.stub(obj, 'meth', fn) is deprecated and will be removed fromthe public API in a future version of sinon.
 Use stub(obj, 'meth').callsFake(fn).
 Codemod available at https://github.com/hurrymaplelad/sinon-codemod

Is this feature still supported?

Yes, but using a different syntax. See the get and set methods at the bottom of http://sinonjs.org/releases/v2.0.0/stubs/. Closing this.

Perfect. Thanks for the quick response!

The new syntax is awesome. But it doesn't tell how a stubbed getter would be restored?

@derwaldgeist Oh, but it does. As I mentioned above, just see the bottom of the page: http://sinonjs.org/releases/v2.3.1/stubs/

P.S. If you feel the docs could be improved, please feel free to push a PR. The docs are in this repo.


A working example

// test.js 
var sinon = require('sinon');

console.log('#getter-stub example')
var obj = { 'foo' : 'foo-val' }
console.log(obj.foo);

var stub = sinon.stub(obj, 'foo').get( () => 'fake-val' );

console.log(obj.foo);
// this won't work as obj.foo returns a value, not the stub 
// - might be possible to improve the API here!
// obj.foo.restore(); 
stub.restore();
console.log(obj.foo);

console.log('\n#value-stub example')

var stub2 = sinon.stub(obj, 'foo').value( 'new-fake-val' );
console.log(obj.foo);

// this won't work for the above reasons
// => TypeError: obj.foo.restore is not a function
// obj.foo.restore();
stub2.restore();
console.log(obj.foo);


Output

$ node test
#getter-stub example
foo-val
fake-val
foo-val

#value-stub example
new-fake-val
foo-val

@fatso83: @fatso83: It was my fault. I tried to stub the getter of an instance of the class. This worked, but the restore() reported Cannot redefine property: <name of the getter>. I now stubbed the getter on the prototype of the class, this works. Thanks for your help.

If you're reading this from a google search you want to read https://sinonjs.org/releases/latest/stubs/ instead!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ljian3377 picture ljian3377  路  3Comments

NathanHazout picture NathanHazout  路  3Comments

zimtsui picture zimtsui  路  3Comments

akdor1154 picture akdor1154  路  4Comments

tinganho picture tinganho  路  3Comments