ctx.mockImplementationOnce(implementation[, onCall])
implementation<Function> | <AsyncFunction> 用作模拟的实现的函数,用于由onCall指定的调用次数。onCall<integer> 将使用implementation的调用次数。如果指定的调用已经发生,则会抛出异常。 默认值: 下一次调用的次数。
此函数用于更改现有模拟的单次调用行为。一旦发生调用 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);
});