mock.method(object, methodName[, implementation][, options])
object
<Object> 其方法被模拟的对象。methodName
<string> | <symbol> 要模拟的object
上的方法的标识符。 如果object[methodName]
不是函数,则会抛出错误。implementation
<Function> | <AsyncFunction> 用作object[methodName]
的模拟实现的可选函数。 默认值:object[methodName]
指定的原始方法。options
<Object> 模拟方法的可选配置选项。 支持以下属性:- 返回: <Proxy> 被模拟的方法。
模拟方法包含一个特殊的
mock
属性,它是MockFunctionContext
的实例,可用于检查和更改模拟方法的行为。
此函数用于在现有对象方法上创建模拟。 以下示例演示了如何在现有对象方法上创建模拟。
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);
});
object
<Object> The object whose method is being mocked.methodName
<string> | <symbol> The identifier of the method onobject
to mock. Ifobject[methodName]
is not a function, an error is thrown.implementation
<Function> | <AsyncFunction> An optional function used as the mock implementation forobject[methodName]
. Default: The original method specified byobject[methodName]
.options
<Object> Optional configuration options for the mock method. The following properties are supported:getter
<boolean> Iftrue
,object[methodName]
is treated as a getter. This option cannot be used with thesetter
option. Default: false.setter
<boolean> Iftrue
,object[methodName]
is treated as a setter. This option cannot be used with thegetter
option. Default: false.times
<integer> The number of times that the mock will use the behavior ofimplementation
. Once the mocked method has been calledtimes
times, it will automatically restore the original behavior. This value must be an integer greater than zero. Default:Infinity
.
- Returns: <Proxy> The mocked method. The mocked method contains a special
mock
property, which is an instance ofMockFunctionContext
, and can be used for inspecting and changing the behavior of the mocked method.
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);
});