From 1cc050eaa89ea0bd42668c3be070111bd2f5ba0f Mon Sep 17 00:00:00 2001 From: Moshe Atlow Date: Thu, 11 Aug 2022 22:27:34 +0300 Subject: [PATCH] assert: add `getCalls` and `reset` to callTracker PR-URL: https://github.com/nodejs/node/pull/44191 Reviewed-By: Erick Wendel Reviewed-By: Benjamin Gruenbaum --- doc/api/assert.md | 83 +++++++++++++ lib/internal/assert/calltracker.js | 117 +++++++++++++----- .../test-assert-calltracker-getCalls.js | 73 +++++++++++ 3 files changed, 239 insertions(+), 34 deletions(-) create mode 100644 test/parallel/test-assert-calltracker-getCalls.js diff --git a/doc/api/assert.md b/doc/api/assert.md index 245ec0d138191f..312aee4ba353d6 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -322,6 +322,47 @@ function func() {} const callsfunc = tracker.calls(func); ``` +### `tracker.getCalls(fn)` + + + +* `fn` {Function}. + +* Returns: {Array} with all the calls to a tracked function. + +* Object {Object} + * `thisArg` {Object} + * `arguments` {Array} the arguments passed to the tracked function + +```mjs +import assert from 'node:assert'; + +const tracker = new assert.CallTracker(); + +function func() {} +const callsfunc = tracker.calls(func); +callsfunc(1, 2, 3); + +assert.deepStrictEqual(tracker.getCalls(callsfunc), + [{ thisArg: this, arguments: [1, 2, 3 ] }]); +``` + +```cjs +const assert = require('node:assert'); + +// Creates call tracker. +const tracker = new assert.CallTracker(); + +function func() {} +const callsfunc = tracker.calls(func); +callsfunc(1, 2, 3); + +assert.deepStrictEqual(tracker.getCalls(callsfunc), + [{ thisArg: this, arguments: [1, 2, 3 ] }]); +``` + ### `tracker.report()` + +* `fn` {Function} a tracked function to reset. + +reset calls of the call tracker. +if a tracked function is passed as an argument, the calls will be reset for it. +if no arguments are passed, all tracked functions will be reset + +```mjs +import assert from 'node:assert'; + +const tracker = new assert.CallTracker(); + +function func() {} +const callsfunc = tracker.calls(func); + +callsfunc(); +// Tracker was called once +tracker.getCalls(callsfunc).length === 1; + +tracker.reset(callsfunc); +tracker.getCalls(callsfunc).length === 0; +``` + +```cjs +const assert = require('node:assert'); + +function func() {} +const callsfunc = tracker.calls(func); + +callsfunc(); +// Tracker was called once +tracker.getCalls(callsfunc).length === 1; + +tracker.reset(callsfunc); +tracker.getCalls(callsfunc).length === 0; +``` + ### `tracker.verify()`