diff --git a/lib/sinon/spy.js b/lib/sinon/spy.js index 104f1ec59..ee372e205 100644 --- a/lib/sinon/spy.js +++ b/lib/sinon/spy.js @@ -31,11 +31,15 @@ } if (types) { + // A new descriptor is needed here because we can only wrap functions + // By passing the original descriptor we would end up trying to spy non-function properties + var descriptor = {}; var methodDesc = sinon.getPropertyDescriptor(object, property); + for (var i = 0; i < types.length; i++) { - methodDesc[types[i]] = spy.create(methodDesc[types[i]]); + descriptor[types[i]] = spy.create(methodDesc[types[i]]); } - return sinon.wrapMethod(object, property, methodDesc); + return sinon.wrapMethod(object, property, descriptor); } return sinon.wrapMethod(object, property, spy.create(object[property])); diff --git a/test/spy-test.js b/test/spy-test.js index 954d78257..02ae02a3f 100644 --- a/test/spy-test.js +++ b/test/spy-test.js @@ -2226,6 +2226,34 @@ assert.equals(spy.length, 3); } + }, + + "getters and setters": { + "it is possible to spy getters": function () { + var object = { + get myProperty() { + return "fb41a645-24fb-4580-b4c0-17d71ecc1c74"; + } + }; + + var descriptor = sinon.spy(object, "myProperty", ["get"]); + var value = object.myProperty; // eslint-disable-line no-unused-vars + + assert.equals(descriptor.get.callCount, 1); + } + }, + + "it is possible to spy setters": function () { + var object = { // eslint-disable-line accessor-pairs + set myProperty(val) { + this.otherProperty = val * 2; + } + }; + + var descriptor = sinon.spy(object, "myProperty", ["set"]); + object.myProperty = 10; // eslint-disable-line no-unused-vars + + assert.equals(descriptor.set.callCount, 1); } }); }(this)); diff --git a/test/stub-test.js b/test/stub-test.js index c59146ccf..5f5d79b9a 100644 --- a/test/stub-test.js +++ b/test/stub-test.js @@ -1796,6 +1796,47 @@ assert.equals(stub.length, 3); } + }, + + "getters and setters": { + "it is possible to stub getters": function () { + var object = { + get myProperty() { + return "4fb82903-6222-45e4-bfeb-a536bfc9734a"; + } + }; + + function fakeGet() { + return "faked myProperty"; + } + + var descriptor = sinon.stub(object, "myProperty", { + get: fakeGet + }); + + assert.equals(object.myProperty, "faked myProperty"); + assert.equals(descriptor.get.callCount, 1); + }, + + "it is possible to stub setters": function () { + var object = { // eslint-disable-line accessor-pairs + set myProperty(val) { + this.otherProperty = val * 2; + } + }; + + function fakeSet() { + this.otherProperty = "faked myProperty"; + } + + var descriptor = sinon.stub(object, "myProperty", { // eslint-disable-line accessor-pairs + set: fakeSet + }); + + object.myProperty = 5; + assert.equals(object.otherProperty, "faked myProperty"); + assert.equals(descriptor.set.callCount, 1); + } } }); }(this));