mock.method(object, methodName[, implementation][, options])


  • object <Object> 方法被模拟的对象。
  • methodName <string> | <symbol> 要模拟的 object 上方法的标识符。如果 object[methodName] 不是一个函数,将会抛出错误。
  • implementation <Function> | <AsyncFunction> 一个可选函数,用作 object[methodName] 的模拟实现。默认值: object[methodName] 指定的原始方法。
  • options <Object> 模拟方法的可选配置选项。支持以下属性:
    • getter <boolean> 如果为 trueobject[methodName] 将被视为一个 getter。此选项不能与 setter 选项同时使用。默认值: false。
    • setter <boolean> 如果为 trueobject[methodName] 将被视为一个 setter。此选项不能与 getter 选项同时使用。默认值: false。
    • times <integer> 模拟将使用 implementation 行为的次数。一旦被模拟的方法被调用 times 次,它将自动恢复原始行为。该值必须是大于零的整数。默认值: Infinity
  • 返回: <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);
});