Skip to content

Commit

Permalink
Merge pull request #918 from fearphage/fix-spy-property-descriptors
Browse files Browse the repository at this point in the history
Fix interaction with spy getters/setters - fixes #917
  • Loading branch information
fatso83 committed Nov 9, 2015
2 parents 6a79d61 + 4dea77c commit 5b0686a
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/sinon/spy.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ var slice = Array.prototype.slice;
var callId = 0;

function spy(object, property, types) {
var descriptor, i, methodDesc;

if (!property && typeof object === "function") {
return spy.create(object);
}
Expand All @@ -27,11 +29,13 @@ function spy(object, property, types) {
}

if (types) {
var methodDesc = sinon.getPropertyDescriptor(object, property);
for (var i = 0; i < types.length; i++) {
methodDesc[types[i]] = spy.create(methodDesc[types[i]]);
descriptor = {};
methodDesc = sinon.getPropertyDescriptor(object, property);

for (i = 0; i < types.length; 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]));
Expand Down
6 changes: 6 additions & 0 deletions test/call-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1268,6 +1268,12 @@
spy.reset();
spy.call(true);
assert.equals(spy.printf("%t"), "true");
},

unmatched: function () {
var spy = sinon.spy();

assert.equals(spy.printf("%λ"), "%λ");
}
}
});
Expand Down
49 changes: 49 additions & 0 deletions test/spy-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,55 @@
assert.isArray(spy.exceptions);
},

"works with getters": function () {
var object = {
get property() {
return 42;
}
};
var spy = sinon.spy(object, "property", ["get"]);

assert.equals(object.property, 42);
assert(spy.get.calledOnce);
},

"works with setters": function () {
var object = {
get test() {
return this.property;
},
set test(value) {
this.property = value * 2;
}
};
var spy = sinon.spy(object, "test", ["set"]);

object.test = 42;
assert(spy.set.calledOnce);
assert(spy.set.calledWith(42));

assert.equals(object.test, 84);
assert.equals(object.property, 84);
},

"works with setters and getters combined": function () {
var object = {
get test() {
return this.property;
},
set test(value) {
this.property = value * 2;
}
};
var spy = sinon.spy(object, "test", ["get", "set"]);

object.test = 42;
assert(spy.set.calledOnce);

assert.equals(object.test, 84);
assert(spy.get.calledOnce);
},

".named": {
"sets displayName": function () {
var spy = sinon.spy();
Expand Down

0 comments on commit 5b0686a

Please sign in to comment.