Skip to content

Commit

Permalink
test_runner: add resetCalls to MockFunctionContext
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
fossamagna authored and danielleadams committed Jan 3, 2023
1 parent 5e167bd commit 5000243
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
8 changes: 8 additions & 0 deletions doc/api/test.md
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,14 @@ test('changes a mock behavior once', (t) => {
});
```

### `ctx.resetCalls()`

<!-- YAML
added: REPLACEME
-->

Resets the call history of the mock function.

### `ctx.restore()`

<!-- YAML
Expand Down
4 changes: 4 additions & 0 deletions lib/internal/test_runner/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ class MockFunctionContext {
}
}

resetCalls() {
this.#calls = [];
}

trackCall(call) {
ArrayPrototypePush(this.#calls, call);
}
Expand Down
17 changes: 17 additions & 0 deletions test/parallel/test-runner-mocking.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down

0 comments on commit 5000243

Please sign in to comment.