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 targos committed Dec 13, 2022
1 parent 102c2dc commit 6bc7b7e
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
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions lib/internal/test_runner/mock.js
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
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 6bc7b7e

Please sign in to comment.