Skip to content

Commit

Permalink
fix #2589: avoid invoking getter as side-effect (#2592)
Browse files Browse the repository at this point in the history
of creating restorerer function. Check for the odd case
where we actually force setting a value through accessor
functions and only look up the value at that time.

The alternative would be more elaborate, check if the
descriptor had a `get` or a `value` field, and then
decide, but this should do the trick.
  • Loading branch information
fatso83 committed Apr 25, 2024
1 parent 9972e1e commit ec4d592
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/sinon/sandbox.js
Expand Up @@ -243,7 +243,7 @@ function Sandbox(opts = {}) {
*/
function getFakeRestorer(object, property, forceAssignment = false) {
const descriptor = getPropertyDescriptor(object, property);
const value = object[property];
const value = forceAssignment && object[property];

function restorer() {
if (forceAssignment) {
Expand Down
14 changes: 14 additions & 0 deletions test/sandbox-test.js
Expand Up @@ -1296,6 +1296,20 @@ describe("Sandbox", function () {
},
);
});

it("do not call getter whilst replacing getter", function () {
const sandbox = this.sandbox;
const fake = sandbox.fake.returns("bar");
const object = {
get foo() {
return fake();
},
};

sandbox.replaceGetter(object, "foo", () => "replacement");

refute(fake.called);
});
});

describe(".replaceSetter", function () {
Expand Down

0 comments on commit ec4d592

Please sign in to comment.