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 的一个实例,可用于检查和更改模拟函数的行为。

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

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

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);
});
  • original <Function> | <AsyncFunction> An optional function to create a mock on. Default: A no-op function.
  • implementation <Function> | <AsyncFunction> An optional function used as the mock implementation for original. This is useful for creating mocks that exhibit one behavior for a specified number of calls and then restore the behavior of original. Default: The function specified by original.
  • options <Object> Optional configuration options for the mock function. The following properties are supported:
    • times <integer> The number of times that the mock will use the behavior of implementation. Once the mock function has been called times times, it will automatically restore the behavior of original. This value must be an integer greater than zero. Default: Infinity.
  • Returns: <Proxy> The mocked function. The mocked function contains a special mock property, which is an instance of MockFunctionContext, and can be used for inspecting and changing the behavior of the mocked function.

This function is used to create a mock function.

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);
});