ctx.mockImplementationOnce(value[, onAccess])


  • value <any> 用作指定由 onAccess 定义的调用编号的模拟实现的值。
  • onAccess <integer> 将使用 value 的调用次数。如果指定的调用已经发生,则会抛出异常。**默认值:**下一次调用的次数。

此函数用于在单次调用中更改现有模拟的行为。一旦调用 onAccess 发生,模拟将恢复到如果未调用 mockImplementationOnce() 时的行为。

【This function is used to change the behavior of an existing mock for a single invocation. Once invocation onAccess has occurred, the mock will revert to whatever behavior it would have used had mockImplementationOnce() not been called.】

下面的示例使用 t.mock.property() 创建了一个模拟函数,调用了该模拟属性,然后将模拟实现更改为下次调用时的不同值,之后再恢复其之前的行为。

【The following example creates a mock function using t.mock.property(), calls the mock property, changes the mock implementation to a different value for the next invocation, and then resumes its previous behavior.】

test('changes a mock behavior once', (t) => {
  const obj = { foo: 1 };

  const prop = t.mock.property(obj, 'foo', 5);

  assert.strictEqual(obj.foo, 5);
  prop.mock.mockImplementationOnce(25);
  assert.strictEqual(obj.foo, 25);
  assert.strictEqual(obj.foo, 5);
});