diff --git a/lib/internal/test_runner/mock/mock.js b/lib/internal/test_runner/mock/mock.js index 4861f31b5f29..3687b042dbff 100644 --- a/lib/internal/test_runner/mock/mock.js +++ b/lib/internal/test_runner/mock/mock.js @@ -359,7 +359,6 @@ class MockPropertyContext { #object; #propertyName; #value; - #originalValue; #descriptor; #accesses; #onceValues; @@ -369,8 +368,7 @@ class MockPropertyContext { this.#accesses = []; this.#object = object; this.#propertyName = propertyName; - this.#originalValue = object[propertyName]; - this.#value = arguments.length > 2 ? value : this.#originalValue; + this.#value = arguments.length > 2 ? value : object[propertyName]; this.#descriptor = ObjectGetOwnPropertyDescriptor(object, propertyName); if (!this.#descriptor) { throw new ERR_INVALID_ARG_VALUE( @@ -476,7 +474,6 @@ class MockPropertyContext { ObjectDefineProperty(this.#object, this.#propertyName, { __proto__: null, ...this.#descriptor, - value: this.#originalValue, }); } } diff --git a/test/parallel/test-runner-mocking.js b/test/parallel/test-runner-mocking.js index 59a919579e76..3556a8fb4fb3 100644 --- a/test/parallel/test-runner-mocking.js +++ b/test/parallel/test-runner-mocking.js @@ -1275,6 +1275,34 @@ test('throws if setting a non-writable property', (t) => { assert.throws(() => { obj.bar = 3; }, { code: 'ERR_INVALID_ARG_VALUE' }); }); +test('restores an accessor property', (t) => { + const obj = { + get foo() { return 'real'; }, + }; + const original = Object.getOwnPropertyDescriptor(obj, 'foo'); + + const prop = t.mock.property(obj, 'foo', 'mocked'); + assert.strictEqual(obj.foo, 'mocked'); + + prop.mock.restore(); + assert.deepStrictEqual(Object.getOwnPropertyDescriptor(obj, 'foo'), original); +}); + +test('accessor property mocks are auto restored after the test finishes', async (t) => { + const obj = { + get foo() { return 'real'; }, + }; + const original = Object.getOwnPropertyDescriptor(obj, 'foo'); + + await t.test('creates an accessor property mock that is auto restored', (t) => { + t.mock.property(obj, 'foo', 'mocked'); + assert.strictEqual(obj.foo, 'mocked'); + }); + + assert.deepStrictEqual(Object.getOwnPropertyDescriptor(obj, 'foo'), original); + assert.strictEqual(obj.foo, 'real'); +}); + test('throws if property does not exist', (t) => { assert.throws(() => { t.mock.property({}, 'doesNotExist', 1);