ctx.mockImplementationOnce(implementation[, onCall])
- 
implementation<Function> | <AsyncFunction> 要用作onCall指定的调用编号的模拟实现的函数。¥ implementation<Function> | <AsyncFunction> The function to be used as the mock's implementation for the invocation number specified byonCall.
- 
onCall<integer> 将使用implementation的调用编号。如果指定的调用已经发生,则抛出异常。默认值:下一次调用的次数。¥ onCall<integer> The invocation number that will useimplementation. If the specified invocation has already occurred then an exception is thrown. Default: The number of the next invocation.
此函数用于更改单个调用的现有模拟的行为。一旦调用 onCall 发生,模拟将恢复到没有调用 mockImplementationOnce() 时它会使用的任何行为。
¥This function is used to change the behavior of an existing mock for a single
invocation. Once invocation onCall has occurred, the mock will revert to
whatever behavior it would have used had mockImplementationOnce() not been
called.
以下示例使用 t.mock.fn() 创建模拟函数,调用模拟函数,将模拟实现更改为下一次调用的不同函数,然后恢复其先前的行为。
¥The following example creates a mock function using t.mock.fn(), calls the
mock function, changes the mock implementation to a different function for the
next invocation, and then resumes its previous behavior.
test('changes a mock behavior once', (t) => {
  let cnt = 0;
  function addOne() {
    cnt++;
    return cnt;
  }
  function addTwo() {
    cnt += 2;
    return cnt;
  }
  const fn = t.mock.fn(addOne);
  assert.strictEqual(fn(), 1);
  fn.mock.mockImplementationOnce(addTwo);
  assert.strictEqual(fn(), 3);
  assert.strictEqual(fn(), 4);
});