typestar

Mocks in JavaScript

t.mock.fn records calls; t.mock.method replaces one on an object.

import test from "node:test";
import assert from "node:assert/strict";

function record(store, lang, tpm) {
  if (tpm <= 0) throw new RangeError("tpm must be positive");
  return store.save(lang, tpm);
}

test("saves through the store", (t) => {
  const save = t.mock.fn(() => "saved");
  const result = record({ save }, "go", 104);

  assert.equal(result, "saved");
  assert.equal(save.mock.callCount(), 1);
  assert.deepEqual(save.mock.calls[0].arguments, ["go", 104]);
});

test("replaces a method for one test", (t) => {
  const clock = { now: () => 0 };
  t.mock.method(clock, "now", () => 1234);
  assert.equal(clock.now(), 1234);
});

How it works

  1. The mock's calls array holds the arguments and the result.
  2. A replaced method is restored when the test ends.
  3. Assert on the call, not on the implementation.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
620
Tokens
184
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 1 of 2 in Mocks & time, step 5 of 9 in Testing with node:test.

← Previous Next →