test_runner: add resetCalls to MockFunctionContext

This commit allows tests in test runner to reset
the calls of mock function

Refs: https://github.com/nodejs/node/pull/45326#discussion_r1014728750
PR-URL: https://github.com/nodejs/node/pull/45710
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Moshe Atlow <moshe@atlow.co.il>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
This commit is contained in:
MURAKAMI Masahiko authored and Michaël Zasso committed 2022-12-13 09:42:42 +00:00
1 parent 102c2dc071
commit 6bc7b7e6f4
3 files changed
+29

No files matched your search

+8
View File
@@ -870,6 +870,14 @@ test('changes a mock behavior once', (t) => {
});
```
### `ctx.resetCalls()`
<!-- YAML
added: REPLACEME
-->
Resets the call history of the mock function.
### `ctx.restore()`
<!-- YAML
+4
View File
@@ -77,6 +77,10 @@ class MockFunctionContext {
}
}
resetCalls() {
this.#calls = [];
}
trackCall(call) {
ArrayPrototypePush(this.#calls, call);
}
+17
View File
@@ -780,6 +780,23 @@ test('local mocks are auto restored after the test finishes', async (t) => {
assert.strictEqual(originalBar, obj.bar);
});
test('reset mock calls', (t) => {
const sum = (arg1, arg2) => arg1 + arg2;
const difference = (arg1, arg2) => arg1 - arg2;
const fn = t.mock.fn(sum, difference);
assert.strictEqual(fn(1, 2), -1);
assert.strictEqual(fn(2, 1), 1);
assert.strictEqual(fn.mock.calls.length, 2);
assert.strictEqual(fn.mock.callCount(), 2);
fn.mock.resetCalls();
assert.strictEqual(fn.mock.calls.length, 0);
assert.strictEqual(fn.mock.callCount(), 0);
assert.strictEqual(fn(3, 2), 1);
});
test('uses top level mock', () => {
function sum(a, b) {
return a + b;