Skip to content

Commit 16b7194

Browse files
committed
test_runner: add resetCalls to MockFunctionContext
This commit allows tests in test runner to reset the calls of mock function Refs: #45326 (comment)
1 parent 8541b3a commit 16b7194

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

doc/api/test.md

Lines changed: 8 additions & 0 deletions
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+
Reset the calls of mock function.
880+
873881
### `ctx.restore()`
874882

875883
<!-- YAML

lib/internal/test_runner/mock.js

Lines changed: 4 additions & 0 deletions
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

Lines changed: 17 additions & 0 deletions
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)