NewNode 26.14: mockResolvedValue and Friends in node:test →
w3/w3-tutorials

Node 26.14: mockResolvedValue and Friends in node:test

Node 26.14 adds mockReturnValue, mockResolvedValue, mockRejectedValue and mockThrownValue to node:test. Use them in a TypeScript suite and fix the missing types.

Updated Dec 4, 20265 min readIntermediatenode 26.14.0 · node 24.23.0 · typescript 7.0.2 · @types/node 26.6.11

Node 26.14 adds four shorthands to the mocks in node:test: mockReturnValue(), mockResolvedValue(), mockRejectedValue() and mockThrownValue(). If you have moved tests over from Jest or Vitest, these are the helpers you missed most. This tutorial uses them to test a small retrying client in TypeScript. It also covers the two things that trip people up: older Node versions don't have them, and @types/node doesn't know about them yet.

What the helpers replace

Before 26.14, every canned value went through mockImplementation():

ts
fetchRate.mock.mockImplementation(() => Promise.resolve(1.08));

Each new method is shorthand for one of those patterns, as the docs describe:

HelperSame as
mockReturnValue(v)mockImplementation(() => v)
mockResolvedValue(v)mockImplementation(() => Promise.resolve(v))
mockRejectedValue(r)mockImplementation(() => Promise.reject(r))
mockThrownValue(v)mockImplementation(() => { throw v; })

They are small, but they make a test say what it means. mockRejectedValue(new Error("ECONNRESET")) reads as "the network fails", without an arrow function and a Promise.reject around it.

1. The code under test

Node 26 runs TypeScript directly by stripping the types, so there's no build step. Start with a package.json:

package.json
{
  "name": "mock-helpers-demo",
  "type": "module",
  "scripts": {
    "test": "node --test"
  }
}

The code takes its dependencies as arguments, which makes them easy to mock. getRate() retries once when the fetch fails:

src/rates.ts
export type FetchRate = (currency: string) => Promise<number>;

export async function getRate(currency: string, fetchRate: FetchRate): Promise<number> {
  try {
    return await fetchRate(currency);
  } catch {
    // One retry for flaky networks, then give up.
    return await fetchRate(currency);
  }
}

export function toCents(amount: string, parse: (s: string) => number): number {
  return Math.round(parse(amount) * 100);
}

2. Write the tests

Each test makes an empty mock with t.mock.fn() and then sets what it returns. Mocks made from t.mock are restored when the test ends.

src/rates.test.ts
import { test } from "node:test";
import assert from "node:assert/strict";
import { getRate, toCents } from "./rates.ts";

test("returns the rate", async (t) => {
  const fetchRate = t.mock.fn<(c: string) => Promise<number>>();
  fetchRate.mock.mockResolvedValue(1.08);

  assert.equal(await getRate("EUR", fetchRate), 1.08);
  assert.equal(fetchRate.mock.callCount(), 1);
});

test("retries once after a failure", async (t) => {
  const fetchRate = t.mock.fn<(c: string) => Promise<number>>();
  fetchRate.mock.mockResolvedValue(1.08);
  fetchRate.mock.mockImplementationOnce(() => Promise.reject(new Error("ECONNRESET")));

  assert.equal(await getRate("EUR", fetchRate), 1.08);
  assert.equal(fetchRate.mock.callCount(), 2);
});

test("gives up after two failures", async (t) => {
  const fetchRate = t.mock.fn<(c: string) => Promise<number>>();
  fetchRate.mock.mockRejectedValue(new Error("ECONNRESET"));

  await assert.rejects(getRate("EUR", fetchRate), { message: "ECONNRESET" });
  assert.equal(fetchRate.mock.callCount(), 2);
});

test("converts to cents", (t) => {
  const parse = t.mock.fn<(s: string) => number>();
  parse.mock.mockReturnValue(19.99);

  assert.equal(toCents("19.99", parse), 1999);
});

test("passes parse errors through", (t) => {
  const parse = t.mock.fn<(s: string) => number>();
  parse.mock.mockThrownValue(new SyntaxError("bad number"));

  assert.throws(() => toCents("abc", parse), SyntaxError);
});

The retry test mixes old and new. mockResolvedValue(1.08) sets the default, and mockImplementationOnce() overrides only the first call. There is no mockRejectedValueOnce(), so one-off behaviour still goes through mockImplementationOnce().

3. Run them

terminal
node --version
npm test
text
v26.14.0

> test
> node --test

✔ returns the rate (1.523958ms)
✔ retries once after a failure (0.117792ms)
✔ gives up after two failures (1.1995ms)
✔ converts to cents (0.104833ms)
✔ passes parse errors through (0.099792ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 100.412792

Node 26 is the Active LTS line. The same suite on Node 24.23.0, the older LTS line that is still supported, fails every test because the methods don't exist there:

text
✖ returns the rate (0.8005ms)
  TypeError [Error]: fetchRate.mock.mockResolvedValue is not a function

If your CI runs on Node 24 or 22 as well, keep using mockImplementation() until you drop those versions.

4. Fix the TypeScript errors

Node only strips types and never checks them. Run the type checker and it fails. The latest @types/node at the time of writing, 26.6.11, doesn't include the new methods:

terminal
npm i -D [email protected] @types/[email protected]
npx tsc
text
src/rates.test.ts(7,18): error TS2339: Property 'mockResolvedValue' does not exist on type 'MockFunctionContext<(c: string) => Promise<number>>'.
src/rates.test.ts(15,18): error TS2339: Property 'mockResolvedValue' does not exist on type 'MockFunctionContext<(c: string) => Promise<number>>'.
src/rates.test.ts(24,18): error TS2339: Property 'mockRejectedValue' does not exist on type 'MockFunctionContext<(c: string) => Promise<number>>'.
src/rates.test.ts(32,14): error TS2339: Property 'mockReturnValue' does not exist on type 'MockFunctionContext<(s: string) => number>'.
src/rates.test.ts(39,14): error TS2339: Property 'mockThrownValue' does not exist on type 'MockFunctionContext<(s: string) => number>'.

Until the types catch up, add them yourself with a module augmentation. This version also checks the values against the mocked function's return type:

src/node-test.d.ts
// Types for the mock helpers added in Node 26.14.
// Delete this file once @types/node ships them.
import "node:test";

type Returned<F> = F extends (...args: any[]) => infer R ? R : unknown;

declare module "node:test" {
  namespace test {
    interface MockFunctionContext<F extends Function> {
      mockReturnValue(value: Returned<F>): void;
      mockResolvedValue(value: Awaited<Returned<F>>): void;
      mockRejectedValue(reason: unknown): void;
      mockThrownValue(value: unknown): void;
    }
  }
}

The tsconfig.json used here:

tsconfig.json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "nodenext",
    "strict": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "erasableSyntaxOnly": true,
    "types": ["node"]
  },
  "include": ["src"]
}

Now npx tsc exits with no output. The types also catch mistakes. Change mockResolvedValue(1.08) to mockResolvedValue("1.08") and you get:

text
src/rates.test.ts(7,36): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

When to use them

Use them for any mock that returns, resolves, rejects or throws one fixed value. That covers most mocks in a typical suite.

Keep mockImplementation() when the result depends on the arguments, when you need a different value per call, or when the project still supports Node 24 or older. The helpers don't make tests faster or change how calls are recorded. They only save typing, so there's no reason to rewrite working tests just to use them.

Next steps

Related tutorials