Skip to content

Testing with generated data: arbitrary<T>() ​

Example-based tests only exercise the inputs you think to write. Property tests state an invariant that must hold for every input, generating hundreds of edge cases automatically—empty arrays, -0, extreme floats, and Unicode strings.

In short

  • Type-driven generators: arbitrary<User>() generates User values from the TypeScript type at build time, just like parseJson<User> generates validators.
  • Automatic shrinking & seeds: check(arbitrary<User>(), property) runs 100 trials and returns a Result with the minimal failing value and its reproduction seed.
  • Works with any runner: run node --test with --import @evobug_com/safe-ts-transform/register, Vitest via the Vite plugin, or bun test via [test] preload in bunfig.toml (Bun).
  • Dev checks on by default in tests: disable them (SAFE_TS_DEV_CHECKS=0) only for benchmarks (why).

A property test ​

average has a bug. Example tests with [1, 2, 3] pass:

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { isErr } from "@evobug_com/safe-ts-std/result";

export function average(values: readonly number[]): number {
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}

test("the average of numbers is a number", () => {
  const result = check(arbitrary<readonly number[]>(), (values) => Number.isFinite(average(values)));
  if (isErr(result)) assert.fail(result.error.message);
});
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitraryWith as __arbitraryWith, genString as __arbString, genNumber as __arbNumber, genSafeInt as __arbSafeInt, genBigInt as __arbBigInt, genBoolean as __arbBoolean, genArray as __arbArray, genPick as __arbPick, genPresent as __arbPresent, type ArbSource as __ArbSource } from "@evobug_com/safe-ts-std/arbitrary"; import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { isErr } from "@evobug_com/safe-ts-std/result";

export function average(values: readonly number[]): number {
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}

test("the average of numbers is a number", () => {
  const result = check(__arbitraryWith<readonly number[]>(__ga0), (values) => Number.isFinite(average(values)));
  if (isErr(result)) assert.fail(result.error.message);
});
// ---- generated by safe-ts: test-data generators ----
function __ga0(s: __ArbSource, d: number): (number)[] {
  return __arbArray(s, d, __arbNumber);
}

The property fails on the first run, for an empty array (0 / 0 is NaN):

text
property failed on run 1 of 100 (seed 2)
  value: []
  reproduce with: { seed: 2, runs: 100 }

After average returns undefined for an empty array, the same test finds the next problem, two numbers whose sum is too large for a double:

text
property failed on run 76 of 100 (seed 2)
  value: [1.7976931348623157e+308, 1.7976931348623157e+308]
  (shrunk 7 times from [76, -0.5, 3688148013121616, -6689216266514612, 1.7976931348623157e+308, 1.7976931348623157e+308, 1e-7, -9007199254740992, 60])
  reproduce with: { seed: 2, runs: 100 }

A run fails when the property returns false, returns an Err, or throws. So assert calls work inside it, and so do properties written in the Result style:

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { isErr } from "@evobug_com/safe-ts-std/result";

type Task = { readonly title: string; readonly priority: 1 | 2 | 3; readonly done: boolean };

export function byPriority(tasks: readonly Task[]): readonly Task[] {
  return [...tasks].sort((a, b) => a.priority - b.priority);
}

test("byPriority keeps every task and puts them in order", () => {
  const result = check(arbitrary<readonly Task[]>(), (tasks) => {
    const sorted = byPriority(tasks);
    assert.equal(sorted.length, tasks.length);
    sorted.forEach((task, i) => assert.ok(i === 0 || (sorted[i - 1]?.priority ?? 0) <= task.priority));
  });
  if (isErr(result)) assert.fail(result.error.message);
});
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitraryWith as __arbitraryWith, genString as __arbString, genNumber as __arbNumber, genSafeInt as __arbSafeInt, genBigInt as __arbBigInt, genBoolean as __arbBoolean, genArray as __arbArray, genPick as __arbPick, genPresent as __arbPresent, type ArbSource as __ArbSource } from "@evobug_com/safe-ts-std/arbitrary"; import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { isErr } from "@evobug_com/safe-ts-std/result";

type Task = { readonly title: string; readonly priority: 1 | 2 | 3; readonly done: boolean };

export function byPriority(tasks: readonly Task[]): readonly Task[] {
  return [...tasks].sort((a, b) => a.priority - b.priority);
}

test("byPriority keeps every task and puts them in order", () => {
  const result = check(__arbitraryWith<readonly Task[]>(__ga0), (tasks) => {
    const sorted = byPriority(tasks);
    assert.equal(sorted.length, tasks.length);
    sorted.forEach((task, i) => assert.ok(i === 0 || (sorted[i - 1]?.priority ?? 0) <= task.priority));
  });
  if (isErr(result)) assert.fail(result.error.message);
});
// ---- generated by safe-ts: test-data generators ----
type __T0 = { "title": string; "priority": (1) | (2) | (3); "done": boolean; };
function __ga1(s: __ArbSource, d: number): (1) | (2) | (3) {
  switch (__arbPick(s, d, 3)) {
    case 0: return 1;
    case 1: return 2;
    default: return 3;
  }
}
function __g0(s: __ArbSource, d: number): __T0 {
  const out: __T0 = { "title": __arbString(s), "priority": __ga1(s, d + 1), "done": __arbBoolean(s) };
  return out;
}
function __ga0(s: __ArbSource, d: number): (__T0)[] {
  return __arbArray(s, d, __g0);
}

check catches what the property throws, and the test runner catches what a test throws or rejects with, so neither needs a try/catch around code that throws a PropagateError (uncaught-propagation knows node:test, Vitest, packages that re-export them like vite-plus/test, and their mocks). For a runner the checker can't follow (a CommonJS re-export), list it in package.json: "safe-ts": { "testRunners": ["@acme/test-kit"] }. Assertions that expect a throw catch what the callback throws: assert.throws(fn) (node:assert and Chai), expect(fn).toThrow(), expect(fn).to.throw(), await expect(promise).rejects.toThrow().

With dev checks on (the Node loader, Vitest), a dev check that stops the property counts as a failure too, and its value is shrunk like any other. A comparator that returns NaN for items without a price fails on two such items, where without the checks the sort would pick some order and the property would pass.

The runner's own API isn't reported either. Vitest (also through vite-plus/test), Jest's @jest/globals, Mocha and Chai are installed packages, but automatic mode doesn't analyze them. A hook such as beforeAll(...) at the top level of a test file throws only when misused, so it isn't reported. Neither is an assertion (expect(x).toBe(y), assert.fail()) in a helper outside any test: it throws to fail the test, and the runner reports it.

check returns a Result rather than throwing, so a forgotten check is an error, not a test that silently passes:

ts
import { test } from "node:test";

import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";

test("titles are never empty", () => {
  check(arbitrary<readonly string[]>(), (titles) => titles.every((title) => title.length > 0));
});
ts
import { test } from "node:test";

import { arbitraryWith as __arbitraryWith, genString as __arbString, genNumber as __arbNumber, genSafeInt as __arbSafeInt, genBigInt as __arbBigInt, genBoolean as __arbBoolean, genArray as __arbArray, genPick as __arbPick, genPresent as __arbPresent, type ArbSource as __ArbSource } from "@evobug_com/safe-ts-std/arbitrary"; import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";

test("titles are never empty", () => {
  check(__arbitraryWith<readonly string[]>(__ga0), (titles) => titles.every((title) => title.length > 0));
});
// ---- generated by safe-ts: test-data generators ----
function __ga0(s: __ArbSource, d: number): (string)[] {
  return __arbArray(s, d, __arbString);
}

What gets generated ​

Every type parseJson<T> accepts: string, number, boolean, bigint, SafeInt, Int<Min, Max>, JsonValue, RawJson, JsonNull, literal types, objects and interfaces, arrays, tuples, unions, Option<T>, Enum<...>, Record over string literal keys or over string (and index signatures), typeof of constants, keyof, T[K], utility and mapped types, unknown, and type aliases, including generic and recursive ones. Values that tend to break code come up often:

TypeBesides random values
number0, -0, ±1, 0.5, the largest safe integers and the next ones, Number.MAX_VALUE, Number.MIN_VALUE, 1e21, numbers of any magnitude
SafeInt0, -0, the largest and smallest safe integers, 32-bit limits
Int<Min, Max>only values in the range, its ends often; shrinks towards the value closest to 0
bigint0n, ±1n, 2^53, 64-bit limits, up to 60 digits
string"", up to 4000 characters, accents, CJK, right-to-left, emoji (two UTF-16 units), combining marks, zero-width and control characters, "__proto__"
arraysempty, short, up to 100 items (shorter when nested)
optional fieldsmissing
unions, Enumevery member, every variant
Record<string, V>, { [key: string]: V }empty, up to 8 entries; keys like "__proto__", "constructor", "toString", "", "a.b", "odd key" and non-ASCII ones; never undefined as a value, since parseJson leaves such keys out
JsonValue, unknownbooleans, numbers, strings, arrays (with undefined items: JSON null) and objects of them, nested; never undefined as a whole or as an object value
RawJson, JsonNullthe same with null where JsonValue has undefined, and null itself

What you won't get: NaN and Infinity (JSON can't hold them, and parseJson never returns them), lone surrogates in strings, and an optional field that is present but undefined. Each run has a size, from 0 on the first run to 100 on the last, that bounds lengths and nesting, so early runs try small values. Recursive types stay finite: past a depth limit, arrays are empty, optional fields missing, and a union takes the member that ends soonest.

A type parseJson can't validate is rejected the same way, with the same rule:

✕ Rejectedjson-type
ts
import { arbitrary } from "@evobug_com/safe-ts-std/arbitrary";

type Event = { readonly name: string; readonly at: Date };

export const events = arbitrary<Event>();

arbitrary also rejects a type whose every value contains another one (type Loop = { readonly next: Loop }), since no value of it can be built.

Same seed, same failure ​

A failure reports its seed. Pass it back, with the same number of runs, and check generates exactly the same values again:

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { isErr } from "@evobug_com/safe-ts-std/result";

test("a name is never longer once trimmed", () => {
  const result = check(arbitrary<string>(), (name) => name.trim().length <= name.length, { seed: 2, runs: 100 });
  if (isErr(result)) assert.fail(result.error.message);
});
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitraryWith as __arbitraryWith, genString as __arbString, genNumber as __arbNumber, genSafeInt as __arbSafeInt, genBigInt as __arbBigInt, genBoolean as __arbBoolean, genArray as __arbArray, genPick as __arbPick, genPresent as __arbPresent, type ArbSource as __ArbSource } from "@evobug_com/safe-ts-std/arbitrary"; import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { isErr } from "@evobug_com/safe-ts-std/result";

test("a name is never longer once trimmed", () => {
  const result = check(__arbitraryWith<string>(__ga0), (name) => name.trim().length <= name.length, { seed: 2, runs: 100 });
  if (isErr(result)) assert.fail(result.error.message);
});
// ---- generated by safe-ts: test-data generators ----
function __ga0(s: __ArbSource, d: number): string {
  return __arbString(s);
}

Without seed, every check picks a new one, so each test run tries different values. When one finds a failure, keep its seed: add the same check with { seed, runs } as a test of its own (a pinned regression run), next to the fix. The random runs keep looking for new failures; the pinned one makes sure this one stays fixed, even after the generators change what a seed produces for other runs. runs (default 100) sets how many. To get values outside check, call arbitrary<T>().generate(Rng.seeded(1)) with an Rng from @evobug_com/safe-ts-std/random.

Keep a failure's seed as a regression run ​

Generated inputs find bugs no type or lint rule can see, including bugs below your code. A property test of a binary message format once failed in one run out of several: a chat message came back with its last character changed. The shrunk counterexample (a few hundred characters instead of thousands) and the printed seed made it a ten-minute diagnosis: Node's TextEncoder.encodeInto sometimes stopped one character short of the end of a buffer that was large enough, and the writer didn't look at what it reported. The fix falls back to encode when encodeInto reports less than the whole string.

Once it is fixed, keep the seed from the report in a test of its own, next to the one that tries new values. That run generates exactly the failing values every time, so the bug can't come back unnoticed, while the other test keeps exploring:

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { isErr } from "@evobug_com/safe-ts-std/result";

/** Writes a chat message into a buffer sized for its worst case (3 bytes per UTF-16 unit). */
export function encodeMessage(text: string): Uint8Array {
  const buffer = new Uint8Array(text.length * 3);
  const { read, written } = new TextEncoder().encodeInto(text, buffer);
  if (read < text.length) return new TextEncoder().encode(text);
  return buffer.subarray(0, written);
}

const survives = (text: string) => new TextDecoder().decode(encodeMessage(text)) === text;

test("a message survives encoding", () => {
  const result = check(arbitrary<string>(), survives);
  if (isErr(result)) assert.fail(result.error.message);
});

// The seed of the failure fixed in encodeMessage: these exact values run every time.
test("a message survives encoding (regression, seed 1849)", () => {
  const result = check(arbitrary<string>(), survives, { seed: 1849, runs: 100 });
  if (isErr(result)) assert.fail(result.error.message);
});
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitraryWith as __arbitraryWith, genString as __arbString, genNumber as __arbNumber, genSafeInt as __arbSafeInt, genBigInt as __arbBigInt, genBoolean as __arbBoolean, genArray as __arbArray, genPick as __arbPick, genPresent as __arbPresent, type ArbSource as __ArbSource } from "@evobug_com/safe-ts-std/arbitrary"; import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { isErr } from "@evobug_com/safe-ts-std/result";

/** Writes a chat message into a buffer sized for its worst case (3 bytes per UTF-16 unit). */
export function encodeMessage(text: string): Uint8Array {
  const buffer = new Uint8Array(text.length * 3);
  const { read, written } = new TextEncoder().encodeInto(text, buffer);
  if (read < text.length) return new TextEncoder().encode(text);
  return buffer.subarray(0, written);
}

const survives = (text: string) => new TextDecoder().decode(encodeMessage(text)) === text;

test("a message survives encoding", () => {
  const result = check(__arbitraryWith<string>(__ga0), survives);
  if (isErr(result)) assert.fail(result.error.message);
});

// The seed of the failure fixed in encodeMessage: these exact values run every time.
test("a message survives encoding (regression, seed 1849)", () => {
  const result = check(__arbitraryWith<string>(__ga0), survives, { seed: 1849, runs: 100 });
  if (isErr(result)) assert.fail(result.error.message);
});
// ---- generated by safe-ts: test-data generators ----
function __ga0(s: __ArbSource, d: number): string {
  return __arbString(s);
}

A seed reproduces the same values only while the type and the generator stay the same: after a change to the type, or to arbitrary in a new SAFE-TS version, it tries other values. For a case that must stay covered whatever changes, also write the shrunk value as an ordinary example test.

Shrinking ​

The first failing value is usually large and noisy. check makes it smaller before reporting it: shorter strings and arrays, smaller numbers, missing optional fields, earlier union members. value in the counterexample is the small one, original the one first generated.

How: every random decision a generator makes is a number, recorded in order (another array item?, which union member, a magnitude, a sign, a character). Shrinking removes, zeroes and lowers those numbers, generates again from the edited list, and keeps the edit if the property still fails. It stops when nothing helps, or after maxShrinks extra property calls (default 1000; 0 turns shrinking off). The result is a local minimum, not always the smallest failing value: a string of emoji can stay emoji when replacing one with a letter would change its length in UTF-16 units and make the property pass.

Check your own data paths ​

Generated values are exactly what parseJson<T> can return for the same T. That makes a good test of code that writes data for something else to read: what you send, your parser must accept.

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { parseJson } from "@evobug_com/safe-ts-std/json";
import { isErr, type Option, q, type Result } from "@evobug_com/safe-ts-std/result";

type Order = {
  readonly id: string;
  readonly lines: readonly { readonly sku: string; readonly quantity: number }[];
  readonly note?: string;
  readonly coupon: Option<"HALF" | "TENOFF">;
};

// An `Order` holds only strings, numbers and literals: `JSON.stringify` can't throw on it.
export function encodeOrder(order: Order): string {
  return JSON.stringify(order);
}

test("every order we encode reads back the same", () => {
  const result = check(arbitrary<Order>(), (order): Result<boolean, unknown> => {
    const text = encodeOrder(order);
    const decoded = q(parseJson<Order>(text));
    return encodeOrder(decoded) === text;
  });
  if (isErr(result)) assert.fail(result.error.message);
});
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { arbitraryWith as __arbitraryWith, genString as __arbString, genNumber as __arbNumber, genSafeInt as __arbSafeInt, genBigInt as __arbBigInt, genBoolean as __arbBoolean, genArray as __arbArray, genPick as __arbPick, genPresent as __arbPresent, type ArbSource as __ArbSource } from "@evobug_com/safe-ts-std/arbitrary"; import { arbitrary, check } from "@evobug_com/safe-ts-std/arbitrary";
import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { parseJson } from "@evobug_com/safe-ts-std/json";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { isErr, type Option, q, type Result } from "@evobug_com/safe-ts-std/result";

type Order = {
  readonly id: string;
  readonly lines: readonly { readonly sku: string; readonly quantity: number }[];
  readonly note?: string;
  readonly coupon: Option<"HALF" | "TENOFF">;
};

// An `Order` holds only strings, numbers and literals: `JSON.stringify` can't throw on it.
export function encodeOrder(order: Order): string {
  return JSON.stringify(order);
}

test("every order we encode reads back the same", () => {
  const result = check(__arbitraryWith<Order>(__g0), (order): Result<boolean, unknown> => {
    const text = encodeOrder(order);
    const __q1 = __jsonParse<Order>(text, __v0); if (__q1 instanceof __qErr) return __q1; const decoded = __q1;
    return encodeOrder(decoded) === text;
  });
  if (isErr(result)) assert.fail(result.error.message);
});
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "id": string; "lines": ({ "sku": string; "quantity": number; })[]; "note"?: string; "coupon": ("HALF") | ("TENOFF") | (undefined); };
function __va1(v: unknown, p: string): __JsonResult<{ "sku": string; "quantity": number; }> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j8 = v["sku"];
  if (typeof __j8 !== "string") return __jsonFail(p + ".sku", "string", __j8);
  const __j9 = __j8;
  const __j10 = v["quantity"];
  if (typeof __j10 !== "number") return __jsonFail(p + ".quantity", "number", __j10);
  const __j11 = __j10;
  const out: { "sku": string; "quantity": number; } = { "sku": __j9, "quantity": __j11 };
  return out;
}
function __va0(v: unknown, p: string): __JsonResult<({ "sku": string; "quantity": number; })[]> {
  if (!Array.isArray(v)) return __jsonFail(p, "array", v);
  const out: ({ "sku": string; "quantity": number; })[] = [];
  for (let __j5 = 0; __j5 < v.length; __j5++) {
  const __j6: unknown = v[__j5];
  const __j12 = __va1(__j6, p + "[" + __j5 + "]");
  if (__jsonIsErr(__j12)) return __j12;
  const __j7 = __j12;
  out.push(__j7);
  }
  return out;
}
function __v0(v: unknown, p: string): __JsonResult<__T0> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j1 = v["id"];
  if (typeof __j1 !== "string") return __jsonFail(p + ".id", "string", __j1);
  const __j2 = __j1;
  const __j3 = v["lines"];
  const __j13 = __va0(__j3, p + ".lines");
  if (__jsonIsErr(__j13)) return __j13;
  const __j4 = __j13;
  const __j14 = v["note"];
  let __j15!: (string) | (undefined);
  __j16: {
  if (typeof __j14 === "string") { __j15 = __j14; break __j16; }
  if (__j14 === undefined || __j14 === null) { __j15 = undefined; break __j16; }
  return __jsonFail(p + ".note", "string | nothing", __j14);
  }
  const __j17 = v["coupon"];
  let __j18!: ("HALF") | ("TENOFF") | (undefined);
  __j19: {
  if (__j17 === "HALF") { __j18 = "HALF"; break __j19; }
  if (__j17 === "TENOFF") { __j18 = "TENOFF"; break __j19; }
  if (__j17 === undefined || __j17 === null) { __j18 = undefined; break __j19; }
  return __jsonFail(p + ".coupon", "\"HALF\" | \"TENOFF\" | nothing", __j17);
  }
  const out = { "id": __j2, "lines": __j4 } as { "id": string; "lines": ({ "sku": string; "quantity": number; })[]; "note"?: string; "coupon": ("HALF") | ("TENOFF") | (undefined); };
  if (__j15 !== undefined) out["note"] = __j15;
  out["coupon"] = __j18;
  return out;
}
// ---- generated by safe-ts: test-data generators ----
function __ga1(s: __ArbSource, d: number): { "sku": string; "quantity": number; } {
  const out: { "sku": string; "quantity": number; } = { "sku": __arbString(s), "quantity": __arbNumber(s) };
  return out;
}
function __ga0(s: __ArbSource, d: number): ({ "sku": string; "quantity": number; })[] {
  return __arbArray(s, d, __ga1);
}
function __ga2(s: __ArbSource, d: number): ("HALF") | ("TENOFF") | (undefined) {
  switch (__arbPick(s, d, 3)) {
    case 0: return undefined;
    case 1: return "HALF";
    default: return "TENOFF";
  }
}
function __g0(s: __ArbSource, d: number): __T0 {
  const out = { "id": __arbString(s), "lines": __ga0(s, d + 1) } as __T0;
  if (__arbPresent(s, d)) out["note"] = __arbString(s);
  out["coupon"] = __ga2(s, d + 1);
  return out;
}

The property is written in the Result style: q(...) returns an Err early (a failed parse, say), and check counts a returned Err as a failure, with its error as the cause.

The test compares the encoded text, not the objects, because JSON changes one thing on the way: -0 comes back as 0, and -0 is among the generated numbers, so assert.deepEqual(decoded, order) fails for quantity: -0. Whether that matters is up to your data; the test makes you decide. A bigint field needs encoding code of its own, since JSON.stringify throws on a bigint and parseJson reads one from a decimal string.

What it doesn't do ​

  • Synchronous properties only. A property that returns a promise fails with a message saying so; check doesn't await it.
  • No custom generators. There is no map, filter or oneOf to build generators by hand; the type is the only input. Values outside the JSON-shaped types (Date, Map, classes) can't be generated, same as with parseJson.
  • No stateful or model-based testing, and no constraints beyond the type: "a positive number" or "a valid email" is a property to check, not a generator.

Rules in this guide: json-type, must-use-result

Sharing setup between the tests of a file ​

A module-level let is mutable global state (no-mutable-global), and so is a module-level const the tests change: one test's changes leak into the next. In a test file (*.test.*, *.spec.*, or one that imports node:test or vitest), one pattern is sanctioned: a module-level let that only the setup and teardown hooks assign (before/beforeAll, beforeEach, after/afterAll, afterEach).

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { beforeEach, test } from "node:test";

type Cart = { count: number; items: string[] };

function createCart(): Cart {
  return { count: 0, items: [] };
}

let cart: Cart = createCart();

beforeEach(() => {
  cart = createCart();
});

test("adding an item counts it", () => {
  cart.count += 1;
  cart.items.push("book");
  assert.equal(cart.count, 1);
});

test("starts empty", () => {
  assert.equal(cart.count, 0);
});

When beforeEach assigns it, every test gets its own value, so the tests may change what it holds. When only before/beforeAll assigns it, the tests share one value, and changing it is still reported: create a fresh one in beforeEach, or in the test.

The tests may assign it too: a value one test builds and a later one uses, when building it again would cost seconds (the tests of a file run in order). Such a value is handed over, not fresh, so changing what it holds is reported like a beforeAll one; assign a new value instead.

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";
import type { Option } from "@evobug_com/safe-ts-std/result";

type Order = { readonly id: string; readonly lines: readonly string[] };

function placeOrder(lines: readonly string[]): Order {
  return { id: `o-${lines.length}`, lines };
}

let placed: Option<Order>;

test("placing an order gives it an id", () => {
  placed = placeOrder(["tea", "cake"]);
  assert.equal(placed.id, "o-2");
});

test("the placed order keeps its lines", () => {
  assert.deepEqual(placed?.lines, ["tea", "cake"]);
});

To set a global for one test, use vi.stubGlobal(name, value) (undone by vi.unstubAllGlobals()): setting globalThis.x from a test function is reported.

A test that restates a constant ​

expect(ENCODING_VERSION).toBe(34) checks that the constant says what it says. It can't catch a bug, and it fails on every intended change of the constant, also when two branches that each bumped it are merged: the code is right, and the copy in the test is stale. pinned-constant-assert reports an equality assertion between a literal and a constant whose value is a literal (imported, a member of an as const table, or one of the test file's own). Test what the constant is for: a round trip that uses it, or a relation it must keep.

ts
import assert from "node:assert/strict";
import { test } from "node:test";

const MAX_UNITS = 500;

test("the unit limit", () => {
  assert.equal(MAX_UNITS, 500);
});
✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

const MAX_UNITS = 500;

function admit(count: number): boolean {
  return count <= MAX_UNITS;
}

test("the unit limit admits the last unit and no more", () => {
  assert.ok(admit(MAX_UNITS));
  assert.ok(!admit(MAX_UNITS + 1));
});

A value that must never change (a wire code old clients still send) can be pinned on purpose: give the assertion a message that says why, assert.equal(Op.Hello, 1, "HELLO is frozen").

Tests that cannot fail ​

A test passes when nothing in it fails. One that checks nothing therefore passes whatever the code does, and still counts as a test: the shortest way to turn a failing test green is to stop it from checking. Each of these passes tsc, the linters and the runner, and each is reported in test files:

WrittenWhy it can't failRule
test("adds", () => { sum(1, 2); })no assertiontest-without-assertion
if (sum(1, 2) === 4) expect(...), an early returnthe assertion is skipped on the path takentest-without-assertion
try { f() } catch (e) { expect(e)... }no assertion runs when nothing throwstest-without-assertion
expect(r).toBe(r), expect(true).toBe(true), expect(x)the outcome doesn't depend on the codeassertion-cannot-fail
expect(sum(1, 2)).toBeDefined()sum returns a number: it is always definedassertion-cannot-fail
const spy = vi.fn(() => 3); expect(spy()).toBe(3)it checks the mock, not the codeassertion-cannot-fail
setTimeout(() => expect(...)), p.then((v) => expect(v)...)it runs after the test has passeddeferred-assertion
try { expect(...) } catch {}the catch takes the failureswallowed-assertion

An assertion is expect(...) with a matcher, assert..., t.assert..., expect.assertions(n), t.plan(n), a subtest, assert.fail(...) on a path the test mustn't take (if (isErr(r)) assert.fail(r.error.message)), or a call of a helper whose every path asserts, also one in another file. The test's paths are read from the shared control-flow layer, so a branch, an early return and a catch mean what they do at run time.

When the point of a test is only that the code doesn't throw, say so, and the test fails with a message that names the throw:

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

function warmUp(sizes: readonly number[]): readonly number[] {
  return sizes.map((size) => size * 2);
}

test("warming up the caches doesn't throw", () => {
  assert.doesNotThrow(() => warmUp([1, 2, 3]));
});
ts
import assert from "node:assert/strict";
import { test } from "node:test";

function warmUp(sizes: readonly number[]): readonly number[] {
  { const __la1 = sizes; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let size = __le1; __lr1[__li1] = (size * 2); }} return __lr1; }
}

test("warming up the caches doesn't throw", () => {
  assert.doesNotThrow(() => warmUp([1, 2, 3]));
});

With Vitest or Jest: expect(() => warmUp(sizes)).not.toThrow(), and for a promise await expect(connect(host)).resolves.not.toThrow() (node:assert: await assert.doesNotReject(p)).

A loop or a forEach whose body asserts counts as asserting: a table-driven test is the usual reason to write one (an adopter has 58 such tests, all over written tables). A list that turns out empty passes the test, and that the checker can't see.

Tests that never run ​

WrittenWhat happensRule
test.only(...), describe.only, { only: true }the other tests of the file stop running; the run passesfocused-test
test.skip(...), .todo, xit, { skip: true }, t.skip(), an empty bodythe test doesn't run; the run passesskipped-test
two test("adds", ...) in one describereports, -t filters and snapshots can't tell them apartduplicate-test-name
describe("cart", () => {}), a test file with no testnode:test passes itempty-test-suite

A skip is allowed with its reason: a comment on the line above, node:test's { skip: "why" } or t.skip("why"), or a condition (test.skipIf(process.platform === "win32")). Every skipped test is counted among the escape hatches, with a reason or without, and a baseline fails the run when there are more than before.

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

function total(prices: readonly number[]): number {
  return prices.reduce((sum, price) => sum + price, 0);
}

test("totals in cents", { skip: "rounding to cents is decided in #41" }, () => {
  assert.equal(total([0.1, 0.2]), 0.3);
});

Partial and fake values ​

A test often needs a value of a big type for one field of it, a fake of a service, or a value of the wrong type on purpose. @evobug_com/safe-ts-std/testing has a helper for each; they say a value has a type without checking it, so test-only-helper reports them outside test files:

HelperGives
fixture<T>(fields)a T from the fields the test needs, at any depth; the others are missing. A plain object, so deepEqual sees what you wrote
testDouble<T>(fields)a fake T; reading a field it wasn't given throws (testDouble: "connect" isn't set), so the test says what the code under test needs
unchecked<T>(value)any value typed T, for feeding code the wrong type on purpose (a validator test)
expectPresent(value, what?)the value, or a failed test when it is undefined or null (querySelector, getContext("2d"))

A cast does the same three jobs without saying which one, so the test still compiles when the type gains a field the code under test reads. In a test file, the help of no-unchecked-cast names these helpers, and with the idiomatic rules on, cast-in-test reports as unknown as T and as never even where no-unchecked-cast is off for tests.

✓ Accepted0 diagnostics
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { validate } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
import { fixture, unchecked } from "@evobug_com/safe-ts-std/testing";

type Invoice = { readonly number: string; readonly total: number; readonly customer: { readonly name: string; readonly email: string } };

function greeting(invoice: Invoice): string {
  return `Dear ${invoice.customer.name}`;
}

test("the greeting uses the customer's name", () => {
  assert.equal(greeting(fixture<Invoice>({ customer: { name: "Ada" } })), "Dear Ada");
});

test("a total sent as text is refused", () => {
  assert.ok(isErr(validate<Invoice>(unchecked<Invoice>({ number: "7", total: "12", customer: { name: "Ada", email: "[email protected]" } }))));
});
ts
import assert from "node:assert/strict";
import { test } from "node:test";

import { parseJsonWith as __jsonParse, validateWith as __jsonValidate, jsonFail as __jsonFail, isJsonErr as __jsonIsErr, isJsonObject as __jsonIsObject, type JsonResult as __JsonResult } from "@evobug_com/safe-ts-std/json"; import { validate } from "@evobug_com/safe-ts-std/json";
import { isErr } from "@evobug_com/safe-ts-std/result";
import { fixture, unchecked } from "@evobug_com/safe-ts-std/testing";

type Invoice = { readonly number: string; readonly total: number; readonly customer: { readonly name: string; readonly email: string } };

function greeting(invoice: Invoice): string {
  return `Dear ${invoice.customer.name}`;
}

test("the greeting uses the customer's name", () => {
  assert.equal(greeting(fixture<Invoice>({ customer: { name: "Ada" } })), "Dear Ada");
});

test("a total sent as text is refused", () => {
  assert.ok(isErr(__jsonValidate<Invoice>(unchecked<Invoice>({ number: "7", total: "12", customer: { name: "Ada", email: "[email protected]" } }), __v0)));
});
// ---- generated by safe-ts: JSON validators ----
type __T0 = { "number": string; "total": number; "customer": { "name": string; "email": string; }; };
function __va0(v: unknown, p: string): __JsonResult<{ "name": string; "email": string; }> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j7 = v["name"];
  if (typeof __j7 !== "string") return __jsonFail(p + ".name", "string", __j7);
  const __j8 = __j7;
  const __j9 = v["email"];
  if (typeof __j9 !== "string") return __jsonFail(p + ".email", "string", __j9);
  const __j10 = __j9;
  const out: { "name": string; "email": string; } = { "name": __j8, "email": __j10 };
  return out;
}
function __v0(v: unknown, p: string): __JsonResult<__T0> {
  if (!__jsonIsObject(v)) return __jsonFail(p, "object", v);
  const __j1 = v["number"];
  if (typeof __j1 !== "string") return __jsonFail(p + ".number", "string", __j1);
  const __j2 = __j1;
  const __j3 = v["total"];
  if (typeof __j3 !== "number") return __jsonFail(p + ".total", "number", __j3);
  const __j4 = __j3;
  const __j5 = v["customer"];
  const __j11 = __va0(__j5, p + ".customer");
  if (__jsonIsErr(__j11)) return __j11;
  const __j6 = __j11;
  const out: { "number": string; "total": number; "customer": { "name": string; "email": string; }; } = { "number": __j2, "total": __j4, "customer": __j6 };
  return out;
}

Use them where a test would otherwise cast. x as unknown as Invoice and x as never say what unchecked<Invoice>(x) says, but nothing tells them from a cast in production code, and a search for them finds both. fixture and testDouble also keep the test honest about what it leaves out: a field the test didn't give is missing, or throws when read, instead of being whatever the cast pretended.

A DOM in Node: jsdom and AbortController ​

Strict code removes its listeners with a signal (addEventListener(type, f, { signal }), see listener-cleanup). jsdom's addEventListener accepts only its own AbortSignal, and throws for Node's (parameter 3 dictionary's 'signal' member is not of type 'AbortSignal'). When a test setup file installs jsdom's globals by hand, install its AbortController with them, so the code under test creates jsdom's signals:

ts
// test/dom-setup.ts, loaded before the tests
import { JSDOM } from "jsdom";

const dom = new JSDOM("<!doctype html><body></body>", { url: "http://localhost/" });
Object.assign(globalThis, {
  window: dom.window,
  document: dom.window.document,
  AbortController: dom.window.AbortController,
});

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra