Augmenting third-party types
Relay’s tests check job ids in a dozen places, and each one repeats the pattern:
expect(/^job_[0-9a-z]{6,}$/.test(id)).toBe(true). When it fails, the message is “expected true, received false”,
and it does not say which id was wrong or what an id should look like. A custom matcher fixes both:
expect(id).toBeValidJobId().
A matcher has two halves. At runtime, expect.extend registers it. For the types, you extend bun:test’s own
interfaces. M4 covered how declare module reopens an interface. This lesson uses it on a
real package, and covers what goes wrong when it does nothing.
The runtime half: expect.extend
Section titled “The runtime half: expect.extend”expect.extend takes an object of matchers. Each is a function that receives the actual value, then the
arguments of the call, and returns { pass, message }:
import { expect } from "bun:test"
const JOB_ID = /^job_[0-9a-z]{6,}$/
expect.extend({ toBeValidJobId(received: unknown) { const pass = typeof received === "string" && JOB_ID.test(received) return { pass, message: () => (pass ? `expected ${String(received)} not to be a valid job id` : `expected ${String(received)} to be a valid job id`) } }})pass says whether the value matched. With .not, Bun inverts it, so message must describe the failure for
the case the user wrote: when pass is true, the failure is “it matched, and should not have”. That is why the
function builds both messages. received is unknown because a matcher can be called on anything, so it
checks typeof itself.
At this point the test runs, and tsc rejects it: Property 'toBeValidJobId' does not exist on type 'Matchers<string>'.
The type half: merge into Matchers
Section titled “The type half: merge into Matchers”bun:test exports Matchers<T>, the type of what expect(value) returns, and AsymmetricMatchers, the type
of what expect.<name>() returns, used inside toEqual. (The names are in
node_modules/bun-types/test.d.ts, and lesson 5 shows how to find such things.) Merge your matcher into both:
import { expect } from "bun:test"
declare module "bun:test" { interface Matchers<T> { toBeValidJobId(): void } interface AsymmetricMatchers { toBeValidJobId(): AsymmetricMatcher }}
export function check(id: string): void { expect(id).toBeValidJobId() expect(id).not.toBeValidJobId() expect({ id }).toEqual({ id: expect.toBeValidJobId() })}Three details:
- Write the type parameters as the original does. Bun declares
Matchers<T = unknown>, andMatchers<T>is accepted. Adding a second parameter is an error:All declarations of 'Matchers' must have identical type parameters. - The signature describes the call site, not the function you passed to
expect.extend. The matcher receivesreceivedfirst, but the caller writestoBeValidJobId(), so the augmentation has no parameters. A call such astoBeValidJobId("job")is now a type error. - The asymmetric form returns
AsymmetricMatcher, the type Bun uses forexpect.any()and friends. Withvoid, it can’t be passed totoEqualas a value.
Nothing connects the two halves. If you add a matcher and forget the declaration, tsc complains. If you declare
one and forget expect.extend, tsc is happy and the test dies with toBeValidJobId is not a function.
Typing the environment: Bun.Env
Section titled “Typing the environment: Bun.Env”Lesson 1 extended NodeJS.ProcessEnv from a script. In a module, extend the interface Bun’s own types use, Env
in the "bun" module. It reaches process.env and Bun.env:
export {}
declare module "bun" { interface Env { RELAY_JOB_PREFIX?: string }}
export const prefix: string = process.env.RELAY_JOB_PREFIX ?? Bun.env.RELAY_JOB_PREFIX ?? "job"Where to put it
Section titled “Where to put it”Put the matcher and its declaration in one file, test/matchers.ts, so they can’t drift apart. Tell Bun to load
it before every test file, in bunfig.toml:
[test]preload = ["./test/matchers.ts"]Without preload, a test file only has the matcher if it happens to import matchers.ts. With it, all test files do.
The tsc half needs its own step: the file must be in the program.
Pitfalls
Section titled “Pitfalls”The file must be a module. A .ts or .d.ts file without a top-level import or export is a script, and
declare module "x" in a script declares a new ambient module. For a package with real types, that
declaration replaces the package’s types for the whole program:
declare module "fast-check" { interface Zed { z: 1 }}With this file in the program, import fc from "fast-check" still resolves, but fc.integer is gone:
Property 'integer' does not exist on type 'typeof import("fast-check")'. bun:test happens to survive this, because
bun-types also declares it as an ambient module, so the two merge. Do not rely on that, and add export {} or an
import every time.
The augmentation must be in the program. TypeScript only reads files it was told about, through include, files
or an import chain. If the file with declare module "bun:test" isn’t one of them, the matcher is unknown in the
tests, even though it runs:
a.test.ts(2,11): error TS2551: Property 'toBeValidJobId' does not exist on type 'Matchers<string>'. Did you mean 'toBe'?Check that your tsconfig include covers test/matchers.ts. A preload does not add a file to the program.
You can only add. Augmentation merges new members into existing interfaces. It can’t change the type of a member that exists, and it can’t edit a function signature, as M4 noted.
Exercise
Section titled “Exercise”Copy these files into the Relay project in one folder, such as src/declarations/augmenting/. Rename
main.starter.ts to main.ts. The starter has a matcher that passes any string and no types. Fix the matcher and
add the declare module "bun:test" block, then run bun test in that folder. The test runs tsc on main.ts and
usage.ts, and usage.ts contains two calls that must be errors.
// Relay's job ids look like "job_a1b2c3": the prefix job_ and six or more lowercase letters or digits.// Every test that checks an id repeats the regex. Make it a custom matcher: expect(id).toBeValidJobId().//// Rules:// - The matcher passes only for strings that match /^job_[0-9a-z]{6,}$/. A number, undefined or an// uppercase id fails.// - On failure, the message contains "to be a valid job id". With .not, a passing id fails with// a message containing "not to be a valid job id".// - Add the type declarations, so that expect(x).toBeValidJobId() and expect.toBeValidJobId() compile// and the matcher takes no arguments. Use `declare module "bun:test"` and merge into// `Matchers<T>` and `AsymmetricMatchers`. The asymmetric form returns `AsymmetricMatcher`.import { expect } from "bun:test"
expect.extend({ toBeValidJobId(received: unknown) { const pass = typeof received === "string" return { pass, message: () => `received ${String(received)}` } }})import { expect } from "bun:test"
export const check = (id: string): void => { expect(id).toBeValidJobId() expect(id).not.toBeValidJobId() expect({ id }).toEqual({ id: expect.toBeValidJobId() })}
// @ts-expect-error: the matcher takes no argumentsexport const extra = (id: string): void => expect(id).toBeValidJobId("job")
// @ts-expect-error: toBeValidJobID (capital D) is a typo, not a registered matcherexport const typo = (id: string): void => expect(id).toBeValidJobID()import { expect, test } from "bun:test"import { existsSync } from "node:fs"import { join } from "node:path"import "./main.ts"
const tsc = [join(import.meta.dir, "../../../node_modules/.bin/tsc"), join(process.cwd(), "node_modules/.bin/tsc")].find(existsSync) ?? "tsc"
test("the augmentation type-checks usage.ts and rejects misuse", () => { const r = Bun.spawnSync( [tsc, "--noEmit", "--strict", "--target", "esnext", "--module", "esnext", "--moduleResolution", "bundler", "--verbatimModuleSyntax", "--allowImportingTsExtensions", "--skipLibCheck", "--ignoreConfig", "--types", "bun", "main.ts", "usage.ts"], { cwd: import.meta.dir } ) expect(r.stdout.toString() + r.stderr.toString()).toBe("") expect(r.exitCode).toBe(0)})
test("passes for well-formed ids", () => { expect("job_a1b2c3").toBeValidJobId() expect("job_0123456789").toBeValidJobId()})
test("fails for anything else, with a message", () => { expect(() => expect("JOB_A1B2C3").toBeValidJobId()).toThrow("to be a valid job id") expect(() => expect("job_abc").toBeValidJobId()).toThrow("to be a valid job id") expect(() => expect("job_ab-cdef").toBeValidJobId()).toThrow("to be a valid job id") expect(() => expect(42).toBeValidJobId()).toThrow("to be a valid job id") expect(() => expect(undefined).toBeValidJobId()).toThrow("to be a valid job id")})
test("works with .not and says why", () => { expect("nope").not.toBeValidJobId() expect(() => expect("job_a1b2c3").not.toBeValidJobId()).toThrow("not to be a valid job id")})
test("works as an asymmetric matcher", () => { expect({ id: "job_a1b2c3", n: 1 }).toEqual({ id: expect.toBeValidJobId(), n: 1 }) expect(() => expect({ id: "bad" }).toEqual({ id: expect.toBeValidJobId() })).toThrow()})expect.extendadds the matcher at runtime. Merging intoMatchers<T>andAsymmetricMatchersindeclare module "bun:test"adds it to the types.- The declaration describes the call (
toBeValidJobId()), not the implementation’sreceivedparameter. - Extend
Bun.Envwithdeclare module "bun"to type environment keys inprocess.envandBun.env. - The augmenting file needs an
importorexport, or it can replace a package’s types. - The file must be in the program (
includeor an import), andpreloadloads it for the runtime.
Further reading
Section titled “Further reading”- TypeScript handbook: Declaration merging, module augmentation: how to extend another module’s types.
- TypeScript handbook: Declaration merging, global augmentation: declare global from inside a module.