mock.fn([original[, implementation]][, options])


  • original <Function> | <AsyncFunction> 一个可选的函数,用于创建模拟对象。 默认值: 一个空操作函数。
  • implementation <Function> | <AsyncFunction> 一个可选函数,用作 original 的模拟实现。这对于创建在指定次数的调用后表现出某种行为的模拟非常有用,然后恢复 original 的行为。默认值: original 指定的函数。
  • options <Object> 模拟函数的可选配置选项。支持以下属性:
    • times <integer> 模拟将使用 implementation 行为的次数。 一旦模拟函数被调用 times 次,它将自动恢复 original 的行为。 此值必须是大于零的整数。 默认值: Infinity
  • 返回值:<Proxy> 模拟函数。模拟函数包含一个特殊的 mock 属性,该属性是 MockFunctionContext 的一个实例,可用于检查和更改模拟函数的行为。

此函数用于创建模拟函数。

【This function is used to create a mock function.】

以下示例创建了一个模拟函数,每次调用时使计数器增加一。times 选项用于修改模拟行为,使前两次调用将计数器增加二而不是一。

【The following example creates a mock function that increments a counter by one on each invocation. The times option is used to modify the mock behavior such that the first two invocations add two to the counter instead of one.】

test('mocks a counting function', (t) => {
  let cnt = 0;

  function addOne() {
    cnt++;
    return cnt;
  }

  function addTwo() {
    cnt += 2;
    return cnt;
  }

  const fn = t.mock.fn(addOne, addTwo, { times: 2 });

  assert.strictEqual(fn(), 2);
  assert.strictEqual(fn(), 4);
  assert.strictEqual(fn(), 5);
  assert.strictEqual(fn(), 6);
});