Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 1 addition & 4 deletions lib/internal/test_runner/mock/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,6 @@ class MockPropertyContext {
#object;
#propertyName;
#value;
#originalValue;
#descriptor;
#accesses;
#onceValues;
Expand All @@ -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(
Expand Down Expand Up @@ -476,7 +474,6 @@ class MockPropertyContext {
ObjectDefineProperty(this.#object, this.#propertyName, {
__proto__: null,
...this.#descriptor,
value: this.#originalValue,
});
}
}
Expand Down
28 changes: 28 additions & 0 deletions test/parallel/test-runner-mocking.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading