SOFTWARE / SYSTEMS / AIEngineering news. Technical depth.
Architecture / 4 MIN READ

Verify callback arguments and call counts with node:test mocks

Check callback arguments and invocation totals with node:test mock records, and learn when to use Node’s dedicated mock assertion helpers.

Create the callback with t.mock.fn(), pass it to the code under test, then inspect callback.mock.callCount() for the invocation total and callback.mock.calls for the arguments. The function’s .mock property exposes its recorded behavior. (Node.js mock function documentation)

Verify the count and arguments together

This example checks that a function invokes its callback exactly twice, passing an item and its index on each invocation:

// callback.test.mjs
import test from 'node:test';
import assert from 'node:assert/strict';

function visitItems(items, onItem) {
  for (let index = 0; index < items.length; index++) {
    onItem(items[index], index);
  }
}

test('visits each item with its index', (t) => {
  const onItem = t.mock.fn();

  visitItems([{ id: 'a' }, { id: 'b' }], onItem);

  assert.strictEqual(onItem.mock.callCount(), 2);

  const calls = onItem.mock.calls;
  assert.deepStrictEqual(calls[0].arguments, [{ id: 'a' }, 0]);
  assert.deepStrictEqual(calls[1].arguments, [{ id: 'b' }, 1]);
});

Run the file with:

node --test callback.test.mjs

callCount() returns the number of times the mock has been invoked. Each entry in calls contains an arguments array holding the arguments passed on that invocation. (Invocation count, call records)

When checking individual records, keep a separate count assertion. Matching the first two calls does not rule out an unwanted third call. Checking the count first also makes a missing invocation fail at the count assertion rather than when accessing a nonexistent record.

Distinguish call indexes from argument indexes

There are two levels of array indexing:

  • onItem.mock.calls[0] selects the first invocation.
  • onItem.mock.calls[0].arguments selects that invocation’s complete argument list.
  • onItem.mock.calls[0].arguments[1] selects the second argument of the first invocation.

Check the complete arguments array when you want to verify every argument supplied on a call. Checking only one element leaves the other arguments unchecked. (Call record fields)

For several invocations, you can compare the ordered argument lists together:

assert.deepStrictEqual(
  onItem.mock.calls.map((call) => call.arguments),
  [
    [{ id: 'a' }, 0],
    [{ id: 'b' }, 1],
  ],
);

Unlike checking individual records, this comparison also checks the number of recorded calls because it compares the complete outer array. A separate count assertion is optional in this form.

Read calls after exercising the code. Its getter returns a copy of the internal call-tracking array, so an array saved before subsequent invocations will not acquire those new entries. When you need only the total, prefer callCount() over calls.length: Node documents it as more efficient because it avoids creating that array copy. (Calls getter, count efficiency)

Dedicated assertions added in Node.js v26.12.0

Node.js documents dedicated mock assertions as added in v26.12.0. On a runtime with these helpers, you can replace the first example’s assertion block with:

t.assert.callCount(onItem, 2);
t.assert.nthCalledWith(onItem, 1, { id: 'a' }, 0);
t.assert.nthCalledWith(onItem, 2, { id: 'b' }, 1);

The two callCount APIs have different jobs: onItem.mock.callCount() returns a number, while t.assert.callCount(onItem, 2) asserts that the invocation total is exactly two. (Count getter method, call-count assertion)

nthCalledWith(fn, n, ...args) checks the specified invocation using the same deep, strict comparison as assert.deepStrictEqual(). Its call number is one-based: nthCalledWith(onItem, 1, ...) checks the record at onItem.mock.calls[0]. Pass expected callback arguments separately, not wrapped in an extra array. (Nth-call assertion)

If only the final invocation’s arguments matter, use:

t.assert.lastCalledWith(onItem, { id: 'b' }, 1);

lastCalledWith() also uses deep, strict comparison, but checks only the most recent invocation. Pair it with a count assertion when duplicate or missing invocations would be a bug. (Last-call assertion)

Do not assume these helpers exist just because mock functions are available. The underlying mock.fn(), calls, and callCount() APIs were added in v18.13.0 and v19.1.0, before the dedicated assertions. Use the record-inspection pattern on runtimes without the newer helpers. (Mock function history, calls history, count history)

Assert after asynchronous work has finished

For asynchronous code, identify the completion boundary before inspecting the mock. If the operation returns a Promise that resolves after all callback invocations, await that Promise and then check the records.

Avoid using an arbitrary delay as proof of completion. A call count describes invocations that have happened so far; an assertion made too early cannot establish the final total. (Invocation count)

The practical pattern is: create the mock, exercise the code, wait for completion if necessary, then verify both the count and the required argument lists.

SOURCES & REVIEW

Sources are linked throughout this guide. Product capabilities can change; consult the linked documentation for your deployment.

Read our editorial approach ↗