method
fun method(target: Any, methodName: String, options: MockFunctionOptions = definedExternally): Mock<Function<*>>(source)
This function is used to create a mock on an existing object method. The following example demonstrates how a mock is created on an existing object method.
test('spies on an object method', (t) => {
const number = {
value: 5,
subtract(a) {
return this.value - a;
},
};
t.mock.method(number, 'subtract');
assert.strictEqual(number.subtract.mock.calls.length, 0);
assert.strictEqual(number.subtract(3), 2);
assert.strictEqual(number.subtract.mock.calls.length, 1);
const call = number.subtract.mock.calls[0];
assert.deepStrictEqual(call.arguments, [3]);
assert.strictEqual(call.result, 2);
assert.strictEqual(call.error, undefined);
assert.strictEqual(call.target, undefined);
assert.strictEqual(call.this, number);
});
Content copied to clipboard
Since
v19.1.0, v18.13.0
Return
The mocked method. The mocked method contains a special mock
property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the behavior of the mocked method.
Parameters
object
The object whose method is being mocked.
methodName
The identifier of the method on object
to mock. If object[methodName]
is not a function, an error is thrown.
implementation
An optional function used as the mock implementation for object[methodName]
.
options
Optional configuration options for the mock method.