Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix: MockPropertyContext distinguish between passing undefined an…
…d not passing value parameter at all

and add test for undefined mock property value
  • Loading branch information
idango10 committed May 26, 2025
commit aaef61a810bcd7dafa7642f34cb9a8c35c4a879f
8 changes: 5 additions & 3 deletions lib/internal/test_runner/mock/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ class MockPropertyContext {
this.#object = object;
this.#propertyName = propertyName;
this.#originalValue = object[propertyName];
this.#value = value ?? this.#originalValue;
this.#value = arguments.length > 2 ? value : this.#originalValue;
this.#descriptor = ObjectGetOwnPropertyDescriptor(object, propertyName);
if (!this.#descriptor) {
throw new ERR_INVALID_ARG_VALUE(
Expand Down Expand Up @@ -677,7 +677,7 @@ class MockTracker {
* Creates a property tracker for a specified object.
* @param {(object)} object - The object whose value is being tracked.
* @param {string} propertyName - The identifier of the property on object to be tracked.
* @param {any} value - A value used as the mock value for object[valueName].
* @param {any} value - An optional replacement value used as the mock value for object[valueName].
* @returns {ProxyConstructor} The mock property tracker.
*/
property(
Expand All @@ -688,7 +688,9 @@ class MockTracker {
validateObject(object, 'object');
validateStringOrSymbol(propertyName, 'propertyName');

const ctx = new MockPropertyContext(object, propertyName, value);
const ctx = arguments.length > 2 ?
new MockPropertyContext(object, propertyName, value) :
new MockPropertyContext(object, propertyName);
ArrayPrototypePush(this.#mocks, {
__proto__: null,
ctx,
Expand Down
13 changes: 13 additions & 0 deletions test/parallel/test-runner-mocking.js
Original file line number Diff line number Diff line change
Expand Up @@ -1152,6 +1152,19 @@ test('changes mocked property value dynamically', (t) => {
assert.strictEqual(obj.foo, undefined);
});

test('mocks property value to undefined', (t) => {
const obj = { foo: 123 };
const prop = t.mock.property(obj, 'foo', undefined);

assert.strictEqual(obj.foo, undefined);
assert.strictEqual(prop.mock.accessCount(), 1);
assert.strictEqual(prop.mock.accesses[0].type, 'get');
assert.strictEqual(prop.mock.accesses[0].value, undefined);

prop.mock.restore();
assert.strictEqual(obj.foo, 123);
});

test('resetAccesses does not affect property value', (t) => {
const obj = { foo: 1 };
const prop = t.mock.property(obj, 'foo', 2);
Expand Down
Loading