mock.method(object, methodName[, implementation][, options])
-
object<Object> 其方法被模拟的对象。¥
object<Object> The object whose method is being mocked. -
methodName<string> | <symbol> 要模拟的object上的方法的标识符。如果object[methodName]不是函数,则会抛出错误。¥
methodName<string> | <symbol> The identifier of the method onobjectto mock. Ifobject[methodName]is not a function, an error is thrown. -
implementation<Function> | <AsyncFunction> 用作object[methodName]的模拟实现的可选函数。默认值:object[methodName]指定的原始方法。¥
implementation<Function> | <AsyncFunction> An optional function used as the mock implementation forobject[methodName]. Default: The original method specified byobject[methodName]. -
options<Object> 模拟方法的可选配置选项。支持以下属性:¥
options<Object> Optional configuration options for the mock method. The following properties are supported:-
getter<boolean> 如果为true,object[methodName]被当作获取器。此选项不能与setter选项一起使用。默认值:false。¥
getter<boolean> Iftrue,object[methodName]is treated as a getter. This option cannot be used with thesetteroption. Default: false. -
setter<boolean> 如果为true,object[methodName]被视为设置器。此选项不能与getter选项一起使用。默认值:false。¥
setter<boolean> Iftrue,object[methodName]is treated as a setter. This option cannot be used with thegetteroption. Default: false. -
times<integer> 模拟将使用implementation的行为的次数。一旦被模拟的方法被调用了times次,它会自动恢复原来的行为。此值必须是大于零的整数。默认值:Infinity。¥
times<integer> The number of times that the mock will use the behavior ofimplementation. Once the mocked method has been calledtimestimes, it will automatically restore the original behavior. This value must be an integer greater than zero. Default:Infinity.
-
-
返回:<Proxy> 被模拟的方法。模拟方法包含一个特殊的
mock属性,它是MockFunctionContext的实例,可用于检查和更改模拟方法的行为。¥Returns: <Proxy> The mocked method. The mocked method contains a special
mockproperty, 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.callCount(), 0);
assert.strictEqual(number.subtract(3), 2);
assert.strictEqual(number.subtract.mock.callCount(), 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);
});