Skip to content

Commit 5000243

Browse files
fossamagnadanielleadams
authored andcommitted
test_runner: add resetCalls to MockFunctionContext
This commit allows tests in test runner to reset the calls of mock function Refs: #45326 (comment) PR-URL: #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 5e167bd commit 5000243

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
@@ -856,6 +856,14 @@ test('changes a mock behavior once', (t) => {
856856
});
857857
```
858858

859+
### `ctx.resetCalls()`
860+
861+
<!-- YAML
862+
added: REPLACEME
863+
-->
864+
865+
Resets the call history of the mock function.
866+
859867
### `ctx.restore()`
860868

861869
<!-- YAML

lib/internal/test_runner/mock.js

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

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

test/parallel/test-runner-mocking.js

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

783+
test('reset mock calls', (t) => {
784+
const sum = (arg1, arg2) => arg1 + arg2;
785+
const difference = (arg1, arg2) => arg1 - arg2;
786+
const fn = t.mock.fn(sum, difference);
787+
788+
assert.strictEqual(fn(1, 2), -1);
789+
assert.strictEqual(fn(2, 1), 1);
790+
assert.strictEqual(fn.mock.calls.length, 2);
791+
assert.strictEqual(fn.mock.callCount(), 2);
792+
793+
fn.mock.resetCalls();
794+
assert.strictEqual(fn.mock.calls.length, 0);
795+
assert.strictEqual(fn.mock.callCount(), 0);
796+
797+
assert.strictEqual(fn(3, 2), 1);
798+
});
799+
783800
test('uses top level mock', () => {
784801
function sum(a, b) {
785802
return a + b;

0 commit comments

Comments
 (0)