Skip to content

Commit

Permalink
feat: throw when trying to use .value() on a method
Browse files Browse the repository at this point in the history
  • Loading branch information
mroderick committed Dec 26, 2024
1 parent 80bc1d9 commit 220bd62
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
15 changes: 15 additions & 0 deletions lib/sinon/default-behaviors.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const arrayProto = require("@sinonjs/commons").prototypes.array;
const isPropertyConfigurable = require("./util/core/is-property-configurable");
const exportAsyncBehaviors = require("./util/core/export-async-behaviors");
const extend = require("./util/core/extend");
const getPropertyDescriptor = require("./util/core/get-property-descriptor");

const slice = arrayProto.slice;

Expand Down Expand Up @@ -286,6 +287,20 @@ const defaultBehaviors = {

value: function value(fake, newVal) {
const rootStub = fake.stub || fake;
const propertyDescriptor = getPropertyDescriptor(
rootStub.rootObj,
rootStub.propName,
);
const propertyIsGetter = propertyDescriptor.get !== undefined;
const propertyIsMethod =
!propertyIsGetter &&
typeof rootStub.rootObj[rootStub.propName] === "function";

if (propertyIsMethod) {
throw new Error(
`${rootStub.propName} is a function, not a getter or value. Use .returns() instead of .value()`,
);
}

Object.defineProperty(rootStub.rootObj, rootStub.propName, {
value: newVal,
Expand Down
23 changes: 23 additions & 0 deletions test/stub-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3781,6 +3781,29 @@ describe("stub", function () {
assert.equals(myFunc.prop, "rawString");
});

it("allows stubbing getters", function () {
const y = {
get foo() {
return "bar";
},
};
refute.exception(function () {
createStub(y, "foo").value("bar");
});
});

it("disallows stubbing non-accessor methods", function () {
const x = {
getFoo: function getFoo() {
return "bar";
},
};

assert.exception(function () {
createStub(x, "getFoo").value("baz");
}, "Error: getFoo is a function, not a getter or value. Use .returns() instead of .value()");
});

it("allows stubbing object props with configurable false", function () {
const myObj = {};
Object.defineProperty(myObj, "prop", {
Expand Down

0 comments on commit 220bd62

Please sign in to comment.