Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix spy.toString when getters on a spy's thisValue throw #2216

Merged
merged 2 commits into from Feb 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 7 additions & 2 deletions lib/sinon/util/core/function-to-string.js
Expand Up @@ -8,9 +8,14 @@ module.exports = function toString() {
while (i--) {
thisValue = this.getCall(i).thisValue;

// eslint-disable-next-line guard-for-in
for (prop in thisValue) {
if (thisValue[prop] === this) {
return prop;
try {
if (thisValue[prop] === this) {
return prop;
}
} catch (e) {
// no-op - accessing props can throw an error, nothing to do here
}
}
}
Expand Down
28 changes: 28 additions & 0 deletions test/util/core/function-to-string-test.js
Expand Up @@ -35,4 +35,32 @@ describe("util/core/functionToString", function() {

assert.equals(functionToString.call(obj.doStuff), "doStuff");
});

// https://github.com/sinonjs/sinon/issues/2215
it("ignores errors thrown by property accessors on thisValue", function() {
var obj = {};

Object.defineProperty(obj, "foo", {
enumerable: true,
get: function() {
throw new Error();
}
});

// this will cause `fn` to be after `foo` when enumerated
obj.fn = function() {
return "foo";
};

// validate that the keys are in the expected order that will cause the bug
var keys = Object.keys(obj);
assert.equals(keys[0], "foo");
assert.equals(keys[1], "fn");

var spy = createSpy(obj, "fn");

obj.fn();

assert.equals(spy.toString(), "fn");
});
});