MockPropertyContext
History
The MockPropertyContext class is used to inspect or manipulate the behavior
of property mocks created via the MockTracker APIs.
ArrayA getter that returns a copy of the internal array used to track accesses (get/set) to the mocked property. Each entry in the array is an object with the following properties:
ctx.accessCount(): integer
integerThis function returns the number of times that the property was accessed.
This function is more efficient than checking ctx.accesses.length because
ctx.accesses is a getter that creates a copy of the internal access tracking array.
ctx.mockImplementation(value): void
anyThis function is used to change the value returned by the mocked property getter.
ctx.mockImplementationOnce(value, onAccess?): void
This function is used to change the behavior of an existing mock for a single
invocation. Once invocation onAccess has occurred, the mock will revert to
whatever behavior it would have used had mockImplementationOnce() not been
called.
The following example creates a mock function using t.mock.property(), calls the
mock property, changes the mock implementation to a different value for the
next invocation, and then resumes its previous behavior.
test('changes a mock behavior once', (t) => { const obj = { foo: 1 }; const prop = t.mock.property(obj, 'foo', 5); assert.strictEqual(obj.foo, 5); prop.mock.mockImplementationOnce(25); assert.strictEqual(obj.foo, 25); assert.strictEqual(obj.foo, 5); });
For consistency with the rest of the mocking API, this function treats both property gets and sets as accesses. If a property set occurs at the same access index, the "once" value will be consumed by the set operation, and the mocked property value will be changed to the "once" value. This may lead to unexpected behavior if you intend the "once" value to only be used for a get operation.
ctx.resetAccesses(): void
Resets the access history of the mocked property.
ctx.restore(): void
Resets the implementation of the mock property to its original behavior. The mock can still be used after calling this function.