Skip to content

Commit 1502b1e

Browse files
fossamagnaErickWendel
authored andcommitted
test_runner: add resetCalls to MockFunctionContext
This commit allows tests in test runner to reset the calls of mock function Refs: nodejs#45326 (comment) PR-URL: nodejs#45710 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
1 parent 0c85ec2 commit 1502b1e

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

doc/api/test.md

+8
Original file line numberDiff line numberDiff line change
@@ -870,6 +870,14 @@ test('changes a mock behavior once', (t) => {
870870
});
871871
```
872872

873+
### `ctx.resetCalls()`
874+
875+
<!-- YAML
876+
added: REPLACEME
877+
-->
878+
879+
Resets the call history of the mock function.
880+
873881
### `ctx.restore()`
874882

875883
<!-- YAML

lib/internal/test_runner/mock.js

+4
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ class MockFunctionContext {
7878
}
7979
}
8080

81+
resetCalls() {
82+
this.#calls = [];
83+
}
84+
8185
trackCall(call) {
8286
ArrayPrototypePush(this.#calls, call);
8387
}

test/parallel/test-runner-mocking.js

+17
Original file line numberDiff line numberDiff line change
@@ -899,6 +899,23 @@ test('local mocks are auto restored after the test finishes', async (t) => {
899899
assert.strictEqual(originalBar, obj.bar);
900900
});
901901

902+
test('reset mock calls', (t) => {
903+
const sum = (arg1, arg2) => arg1 + arg2;
904+
const difference = (arg1, arg2) => arg1 - arg2;
905+
const fn = t.mock.fn(sum, difference);
906+
907+
assert.strictEqual(fn(1, 2), -1);
908+
assert.strictEqual(fn(2, 1), 1);
909+
assert.strictEqual(fn.mock.calls.length, 2);
910+
assert.strictEqual(fn.mock.callCount(), 2);
911+
912+
fn.mock.resetCalls();
913+
assert.strictEqual(fn.mock.calls.length, 0);
914+
assert.strictEqual(fn.mock.callCount(), 0);
915+
916+
assert.strictEqual(fn(3, 2), 1);
917+
});
918+
902919
test('uses top level mock', () => {
903920
function sum(a, b) {
904921
return a + b;

0 commit comments

Comments
 (0)