GeezerVison is showing github.com — test_runner: add resetCalls to MockFunctionContext · nodejs/node@5000243
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: doc/api/test.md +8Lines changed: 8 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -856,6 +856,14 @@ test('changes a mock behavior once', (t) => { |
856 | 856 | }); |
857 | 857 | ``` |
858 | 858 |
|
| 859 | +### `ctx.resetCalls()` |
| 860 | + |
| 861 | +<!-- YAML |
| 862 | +added: REPLACEME |
| 863 | +--> |
| 864 | + |
| 865 | +Resets the call history of the mock function. |
| 866 | + |
859 | 867 | ### `ctx.restore()` |
860 | 868 |
|
861 | 869 | <!-- YAML |
|
Collapse file
Copy file name to clipboardExpand all lines: lib/internal/test_runner/mock.js +4Lines changed: 4 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -77,6 +77,10 @@ class MockFunctionContext { |
77 | 77 | } |
78 | 78 | } |
79 | 79 |
|
| 80 | + resetCalls() { |
| 81 | + this.#calls = []; |
| 82 | + } |
| 83 | + |
80 | 84 | trackCall(call) { |
81 | 85 | ArrayPrototypePush(this.#calls, call); |
82 | 86 | } |
|
Collapse file
Copy file name to clipboardExpand all lines: test/parallel/test-runner-mocking.js +17Lines changed: 17 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -780,6 +780,23 @@ test('local mocks are auto restored after the test finishes', async (t) => { |
780 | 780 | assert.strictEqual(originalBar, obj.bar); |
781 | 781 | }); |
782 | 782 |
|
| 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 | + |
783 | 800 | test('uses top level mock', () => { |
784 | 801 | function sum(a, b) { |
785 | 802 | return a + b; |
|