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的实例,可用于检查和更改模拟方法的行为。
此函数用于在现有对象方法上创建模拟。以下示例演示了如何在现有对象方法上创建模拟。
【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);
});