Created
June 28, 2017 08:22
-
-
Save fatso83/515baa042a7c06cdd18c73ec751ff994 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const someFunction = function(){ | |
return this.value; | |
} | |
function Constructor(){ }; | |
Constructor.prototype.es = { | |
foobar : 'heisann', | |
value : 100 | |
}; | |
Object.defineProperty(Constructor.prototype.es, 'method', { | |
get: function() { | |
return someFunction.bind(this); | |
}, | |
writeable: true, | |
configurable:true | |
}); | |
module.exports = Constructor; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Constructor = require('./constructor'); | |
const instance = new Constructor(); | |
const sinon = require('sinon'); | |
console.log(instance.es.method()) // => 100 | |
// using this won't work: | |
// sinon.stub(instance.__proto__.es, 'method').returns(42); | |
// because the getter is returning a _new_ function each time | |
// therefore you need to attack the actual getter function: | |
const stub = sinon.stub(instance.__proto__.es, 'method').value(()=>42); | |
console.log(instance.es.method()) // => 42 | |
stub.get(()=>()=>84); | |
console.log(instance.es.method()) // => 84 | |
stub.restore(); | |
console.log(instance.es.method()) // => 100 | |
// the above is working on the prototype, can't we do this on the instance? | |
// yes, we can, but remember that the `es` object is shared, so we | |
// can avoid modifying it by shadowing it further down the prototype | |
instance.es = { method: sinon.stub().returns(256) }; | |
console.log(instance.es.method()) // => 256 | |
delete instance.es | |
console.log(instance.es.method()) // => 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment