diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index bdca99dd4..32104f39c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -65,7 +65,7 @@ jobs: npm run unimported browser-test: - runs-on: ubuntu-latest + runs-on: ubuntu-22.04 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 diff --git a/lib/sinon/default-behaviors.js b/lib/sinon/default-behaviors.js index b4530b67b..b12f705f5 100644 --- a/lib/sinon/default-behaviors.js +++ b/lib/sinon/default-behaviors.js @@ -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; @@ -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, diff --git a/test/stub-test.js b/test/stub-test.js index 492db8e3d..3ccf9a6b0 100644 --- a/test/stub-test.js +++ b/test/stub-test.js @@ -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", {