| | |

Jest 23 ๐Ÿƒ Custom Matchers โ€” expect.extend and Domain-Specific Assertions

โฑ๏ธ Estimated read: 19 min | |

Jest ships with a fixed set of matchers: toBe, toEqual, toContain, toThrow, and the rest. They cover general-purpose assertions well, but every codebase eventually develops domain-specific concepts that the built-in matchers cannot express cleanly. A payment amount that must be within one cent of the expected value. A date that must fall inside a business-hours window. A validation result that must carry a specific error code. Writing these assertions inline with expect(Math.abs(actual - expected)).toBeLessThan(0.01) works, but it scatters domain knowledge across every test file and produces failure messages that say nothing about what went wrong.

expect.extend is Jest’s mechanism for solving that problem. It registers custom matchers that are called exactly like the built-in onesโ€”same expect(actual).toBeSomething(expected) syntaxโ€”and it is the supported extension point that the Jest team designed for this purpose. The matchers live in one module, the domain logic lives in one place, and the failure messages are written once. This chapter covers the matcher contract, the asymmetric matcher form that makes custom matchers composable, and the TypeScript augmentation that gives them type safety.

The sections that follow walk through the structure of a custom matcher, the expect.extend registration and its this context, the expect.any-style asymmetric form, the TypeScript typing, and the patterns that keep a matcher suite maintainable.

Key point: A custom matcher is a function that returns { pass: boolean, message: () => string }, registered through expect.extend({ ... }) so it becomes available on every expect call; the message function is what makes the matcher worth writing, because it turns a bare boolean failure into a domain-specific explanation.


Why custom matchers exist

The expressiveness gap. The built-in matchers are general. toBe checks identity, toEqual checks deep equality, toContain checks membership. None of them knows what a “valid payment” or a “business-hours timestamp” is. Without a custom matcher, the test author expresses the domain rule with primitive matchers, and the rule’s intent is buried in the composition.

The failure-message problem. When a primitive composition fails, the message describes the primitive, not the domain. expect(Math.abs(actual - expected)).toBeLessThan(0.01) fails with something like “expected 0.023 to be less than 0.01″โ€”technically correct, but it does not say “the payment amount is off by more than one cent.” A custom matcher’s message function produces the second kind of message.

The duplication problem. A domain rule that appears in forty tests is forty copies of the same composition. When the rule changesโ€”the tolerance moves from one cent to half a centโ€”forty tests need editing. A custom matcher centralizes the rule in one function, and the forty tests keep calling the same matcher.

The composability requirement. A custom matcher that works only as expect(actual).toBeValidPayment() is useful, but a matcher that also works inside toEqual‘s structural comparison is far more powerful. The asymmetric formโ€”expect.validPayment()โ€”lets the matcher participate in object and array comparisons, which is what makes it composable.

The typing gap. JavaScript’s expect has no type information for a custom matcher until the type is declared. The declare global augmentation is what closes the gap, and it is the difference between a matcher that autocompletes and one that produces a red squiggle.

The maintenance trade-off. Every custom matcher is code that must be maintained, documented, and tested. A matcher used once is overhead; a matcher used across a suite is leverage. The decision to write one is a decision about reuse, not about capability.


a. The matcher contract

A custom matcher is a function that receives the actual value and the expected arguments and returns an object with two required properties: pass and message. The pass boolean is the assertion result, and message is a function that returns the failure explanation. The message function is called only when pass is false for a positive assertion, so the string is the failure text the developer sees.

// A matcher that checks a value is within a tolerance of the expected number
function toBeWithinTolerance(received: number, expected: number, tolerance: number) {
  const difference = Math.abs(received - expected);
  return {
    // pass: true when the difference is within the tolerance
    pass: difference <= tolerance,
    // message: called only on failure, explains the gap
    message: () =>
      `expected ${received} to be within ${tolerance} of ${expected} ` +
      `(difference was ${difference.toFixed(4)})`,
  };
}

The received parameter is the value inside expect(...), and the remaining parameters are the matcher’s arguments. The naming convention is received for the actual value and expected for the first argument, because Jest’s own failure messages use that vocabulary. The message function is lazyโ€”Jest calls it only when it needs the failure textโ€”so the string is built only when the assertion fails.

The matcher can also inspect the this context, which carries isNot, promise, and equals. The isNot flag lets the matcher produce a different message for a .not assertion, because “expected X to be within tolerance” reads differently when the assertion is negated.

function toBeWithinTolerance(received: number, expected: number, tolerance: number) {
  const difference = Math.abs(received - expected);
  const pass = difference <= tolerance;
  // this.isNot is true when the matcher is called via .not
  const message = this.isNot
    ? () => `expected ${received} NOT to be within ${tolerance} of ${expected}`
    : () => `expected ${received} to be within ${tolerance} of ${expected} ` +
             `(difference was ${difference.toFixed(4)})`;
  return { pass, message };
}

The this context is typed as MatcherContext in TypeScript. The context also carries promise, which is the string "rejects" or "resolves" when the matcher is used on a promise, and the matcher can branch on it to produce a promise-aware message.


b. expect.extend and registration

expect.extend registers the matchers, and the registration is global to the test file’s expect. The function accepts an object whose keys are the matcher names and whose values are the matcher functions. The registration must run before the first test that uses the matcher, which in practice means the matcher module is imported at the top of the test file or in the setupFilesAfterEnv setup file.

// matchers/tolerance.ts โ€” the matcher module
export function toBeWithinTolerance(received: number, expected: number, tolerance: number) {
  const difference = Math.abs(received - expected);
  return {
    pass: difference <= tolerance,
    message: () =>
      `expected ${received} to be within ${tolerance} of ${expected} ` +
      `(difference was ${difference.toFixed(4)})`,
  };
}
// setup/jest.setup.ts โ€” the registration, run once per test file
import { expect } from "@jest/globals";
import { toBeWithinTolerance } from "../matchers/tolerance";

expect.extend({
  toBeWithinTolerance, // the key is the matcher name
});

The setup file is registered in jest.config.js under setupFilesAfterEnv, which runs after the test framework is installed and before the test file’s own code. The alternative is a direct import in each test file, which is explicit but repetitive. The setup-file approach is the standard for a suite-wide matcher.

The matcher name convention is toBe or toHave prefixed, matching the built-in matchers. Jest does not enforce the prefix, but the convention makes the custom matcher indistinguishable from a built-in one at the call site, which is the point.

// The test file โ€” the matcher is available after the setup import
test("payment amount is within one cent", () => {
  const payment = calculatePayment(100.0);
  // Called exactly like a built-in matcher
  expect(payment).toBeWithinTolerance(100.0, 0.01);
});

The registration replaces any matcher with the same name, so a custom toBe would shadow the built-in one. That is a footgun, not a featureโ€”the matcher names should be distinct from the built-ins, and the domain-specific names are naturally distinct.


c. The asymmetric form

The matcher form covers expect(actual).toBeSomething(expected). The asymmetric form covers expect.something(expected), which is the form that composes inside toEqual, toHaveBeenCalledWith, and array matching. The asymmetric matcher returns an object with an asymmetricMatch method and an optional toString method.

// The asymmetric form: expect.validPayment() composes inside toEqual
export function validPayment(expected: { amount: number; currency: string }) {
  return {
    // asymmetricMatch: the function Jest calls during a structural comparison
    asymmetricMatch(received: unknown): boolean {
      if (typeof received !== "object" || received === null) return false;
      const payment = received as { amount?: unknown; currency?: unknown };
      return (
        typeof payment.amount === "number" &&
        Math.abs(payment.amount - expected.amount) <= 0.01 &&
        payment.currency === expected.currency
      );
    },
    // toString: the text shown in the failure message
    toString(): string {
      return `ValidPayment(${expected.amount} ${expected.currency})`;
    },
  };
}

The asymmetricMatch function is called by Jest’s equality algorithm when it compares the received value to the asymmetric matcher. The toString method produces the label in the diff, which is why it should read as a noun phrase rather than a sentence.

The registration follows the same expect.extend pattern, but the matcher function is called with the expected arguments onlyโ€”the received value is passed to asymmetricMatch later, during the comparison.

// The registration โ€” same expect.extend call
expect.extend({
  validPayment: (expected: { amount: number; currency: string }) => validPayment(expected),
});
// The usage โ€” composes inside a structural comparison
test("the order contains a valid payment", () => {
  const order = { id: "ord-1", payment: { amount: 100.0, currency: "USD" } };
  // validPayment() is an asymmetric matcher inside toEqual
  expect(order).toEqual({
    id: "ord-1",
    payment: expect.validPayment({ amount: 100.0, currency: "USD" }),
  });
});

The asymmetric form is the composable form. It works anywhere a value is comparedโ€”toEqual, toHaveBeenCalledWith, expect.arrayContainingโ€”which is what makes it a first-class assertion rather than a one-off function.


d. TypeScript augmentation

The custom matcher is invisible to TypeScript until the type is declared. The declare global block augments the jest.Matchers interface with the new matcher signature, and that is what gives the matcher autocompletion and type checking at the call site.

// matchers/tolerance.d.ts โ€” the type augmentation
import type { MatcherFunction } from "expect";

// The matcher's type signature: received is number, args are number, number
declare global {
  namespace jest {
    interface Matchers<R> {
      toBeWithinTolerance(expected: number, tolerance: number): R;
    }
  }
}

export {};

The MatcherFunction type is the shape of the matcher implementation. The augmentation declares the matcher on jest.Matchers, which is the interface the expect return type uses. The R generic is the return type of expect, which is void in the normal case and a Promise<void> when the matcher is used with resolves or rejects.

The asymmetric form needs a different augmentation. The expect.validPayment call is a static property on the expect object, so the type is declared on the expect namespace rather than the Matchers interface.

// matchers/valid-payment.d.ts โ€” the asymmetric type augmentation
declare global {
  namespace jest {
    interface Expect {
      // The static expect.validPayment form
      validPayment(expected: { amount: number; currency: string }): {
        asymmetricMatch(received: unknown): boolean;
        toString(): string;
      };
    }
    interface Matchers<R> {
      // The expect(actual).validPayment form, if the matcher has both
      validPayment(expected: { amount: number; currency: string }): R;
    }
  }
}

export {};

The .d.ts file is a declaration file, and it needs to be included in the TypeScript compilationโ€”either listed in tsconfig.json‘s include or imported from the setup file. The export {} at the bottom turns the file into a module, which is required for declare global to work inside a file that also has imports.


e. Promise-aware matchers

A matcher used with resolves or rejects receives a promise as the received value. The matcher’s this.promise is the string "resolves" or "rejects", and the matcher branches on it to produce the correct message and to decide whether to await the received value.

// A promise-aware matcher โ€” it awaits the received value when it is a promise
export async function toBeValidPayment(
  this: jest.MatcherContext,
  received: unknown,
  expected: { amount: number; currency: string }
) {
  // When used with resolves/rejects, received is a promise; await it
  const actual = this.promise ? await received : received;
  const payment = actual as { amount?: unknown; currency?: unknown } | null;
  const pass =
    payment !== null &&
    typeof payment === "object" &&
    typeof payment.amount === "number" &&
    Math.abs(payment.amount - expected.amount) <= 0.01 &&
    payment.currency === expected.currency;
  return {
    pass,
    message: () =>
      this.isNot
        ? `expected payment NOT to be valid (${expected.amount} ${expected.currency})`
        : `expected payment to be ${expected.amount} ${expected.currency}, ` +
          `received ${JSON.stringify(actual)}`,
  };
}

The async matcher is supportedโ€”Jest awaits the matcher’s returned promise before using the result. The this.promise flag is what distinguishes the .resolves form from the direct form, and the await received unwraps the promise when the flag is set.

// The usage โ€” the same matcher on a promise
test("the payment service returns a valid payment", async () => {
  await expect(fetchPayment()).resolves.toBeValidPayment({ amount: 100.0, currency: "USD" });
});

f. Organizing a matcher suite

A matcher suite grows past one matcher quickly. The organization that keeps it maintainable is one file per matcher, a barrel file that exports them, and a single setup registration that imports the barrel. The test file imports nothing but the setup, and the matchers are available on every expect.

// matchers/index.ts โ€” the barrel
export { toBeWithinTolerance } from "./tolerance";
export { toBeValidPayment } from "./valid-payment";
export { toBeBusinessHours } from "./business-hours";
// setup/jest.setup.ts โ€” the single registration
import { expect } from "@jest/globals";
import * as matchers from "../matchers";

expect.extend(matchers); // every matcher registered at once

The barrel exports the implementation functions, and expect.extend accepts the whole object because the matcher names are the exported names. The .d.ts files are separate because the declaration files augment the global namespace, and the augmentation must be visible to the compiler without importing the implementation.

The matcher suite also needs its own tests. A matcher that produces the wrong pass value is a bug that hides every assertion that uses it, so the matcher’s own tests are as important as the tests that consume it.

// matchers/tolerance.test.ts โ€” the matcher's own test
import { toBeWithinTolerance } from "./tolerance";

test("passes when within tolerance", () => {
  const result = toBeWithinTolerance(100.005, 100.0, 0.01);
  expect(result.pass).toBe(true);
});

test("fails when outside tolerance", () => {
  const result = toBeWithinTolerance(100.02, 100.0, 0.01);
  expect(result.pass).toBe(false);
  // The message function produces the failure text
  expect(result.message()).toContain("difference was 0.0200");
});

The matcher test calls the implementation directly rather than through expect, which is why the implementation is exported as a plain function. The pass boolean and the message() string are the two things to assert, and both are covered by the two tests.


Complete Example Session

// ============================================
// PART 1: THE MATCHER IMPLEMENTATION
// ============================================
export function toBeWithinTolerance(
  this: jest.MatcherContext,
  received: number,
  expected: number,
  tolerance: number
) {
  const difference = Math.abs(received - expected);
  return {
    pass: difference <= tolerance, // true when the gap is small enough
    message: () =>
      this.isNot
        ? `expected ${received} NOT to be within ${tolerance} of ${expected}`
        : `expected ${received} to be within ${tolerance} of ${expected} ` +
          `(difference was ${difference.toFixed(4)})`,
  };
}

// ============================================
// PART 2: THE ASYMMETRIC FORM
// ============================================
export function validPayment(expected: { amount: number; currency: string }) {
  return {
    asymmetricMatch(received: unknown): boolean {
      if (typeof received !== "object" || received === null) return false;
      const p = received as { amount?: unknown; currency?: unknown };
      return (
        typeof p.amount === "number" &&
        Math.abs(p.amount - expected.amount) <= 0.01 &&
        p.currency === expected.currency
      );
    },
    toString(): string {
      return `ValidPayment(${expected.amount} ${expected.currency})`;
    },
  };
}

// ============================================
// PART 3: THE REGISTRATION
// ============================================
import { expect } from "@jest/globals";

expect.extend({
  toBeWithinTolerance, // the function name becomes the matcher name
  validPayment: (expected: { amount: number; currency: string }) =>
    validPayment(expected), // the asymmetric form
});

// ============================================
// PART 4: THE TYPE AUGMENTATION
// ============================================
declare global {
  namespace jest {
    interface Matchers<R> {
      toBeWithinTolerance(expected: number, tolerance: number): R;
    }
    interface Expect {
      validPayment(expected: { amount: number; currency: string }): {
        asymmetricMatch(received: unknown): boolean;
        toString(): string;
      };
    }
  }
}

// ============================================
// PART 5: THE MATCHER TEST
// ============================================
test("passes within tolerance", () => {
  const result = toBeWithinTolerance(100.005, 100.0, 0.01);
  expect(result.pass).toBe(true);
});

test("fails outside tolerance", () => {
  const result = toBeWithinTolerance(100.02, 100.0, 0.01);
  expect(result.pass).toBe(false);
  expect(result.message()).toContain("difference was 0.0200");
});

// ============================================
// PART 6: THE CONSUMER TEST
// ============================================
test("payment matches", () => {
  const payment = calculatePayment(100.0);
  expect(payment).toBeWithinTolerance(100.0, 0.01); // the matcher form
});

test("order contains a valid payment", () => {
  const order = { id: "ord-1", payment: { amount: 100.0, currency: "USD" } };
  expect(order).toEqual({
    id: "ord-1",
    payment: expect.validPayment({ amount: 100.0, currency: "USD" }), // asymmetric
  });
});

// ============================================
// PART 7: THE PROMISE-AWARE FORM
// ============================================
export async function toBeValidPayment(
  this: jest.MatcherContext,
  received: unknown,
  expected: { amount: number; currency: string }
) {
  const actual = this.promise ? await received : received;
  const p = actual as { amount?: unknown; currency?: unknown } | null;
  const pass =
    p !== null && typeof p === "object" &&
    typeof p.amount === "number" &&
    Math.abs(p.amount - expected.amount) <= 0.01 &&
    p.currency === expected.currency;
  return {
    pass,
    message: () =>
      this.isNot
        ? `expected payment NOT to be valid`
        : `expected ${expected.amount} ${expected.currency}, received ${JSON.stringify(actual)}`,
  };
}

// ============================================
// PART 8: THE RESOLVES USAGE
// ============================================
test("the service returns a valid payment", async () => {
  await expect(fetchPayment()).resolves.toBeValidPayment({
    amount: 100.0,
    currency: "USD",
  });
});

// ============================================
// PART 9: THE SETUP FILE
// ============================================
// jest.config.js
module.exports = {
  setupFilesAfterEnv: ["<rootDir>/setup/jest.setup.ts"],
};

// ============================================
// PART 10: THE BARREL REGISTRATION
// ============================================
import * as matchers from "../matchers";
expect.extend(matchers); // every matcher in the barrel, one call

The ten parts covered the matcher implementation, the asymmetric form, the registration, the type augmentation, the matcher’s own test, the consumer test, the promise-aware variant, the resolves usage, the setup file config, and the barrel registration.


Quick Reference

The Matcher Contract

PropertyTypePurpose
passbooleanThe assertion result
message() => stringThe failure text
receivedfirst paramThe value inside expect()
this.isNotbooleanTrue for .not assertions
this.promisestring | undefined"resolves" or "rejects"
this.equalsfunctionJest’s deep equality

The Registration

CallEffect
expect.extend({ name: fn })Registers expect(x).name()
expect.extend(matchers)Registers every exported matcher
setupFilesAfterEnvRuns the registration per test file

The Asymmetric Form

MethodPurpose
asymmetricMatch(received)The comparison function
toString()The label in the failure diff
expect.name(arg)The call site inside toEqual

TypeScript Augmentation

InterfacePurpose
jest.Matchers<R>The expect(x).name() signature
jest.ExpectThe static expect.name() signature
jest.MatcherContextThe this type inside the matcher

Best Practices

โœ… Do This:

// Return pass and a lazy message function
return { pass: difference <= tolerance, message: () => `...` };   // โœ…

// Branch the message on this.isNot
const message = this.isNot ? () => `NOT ...` : () => `...`;        // โœ…

// Await the received value when this.promise is set
const actual = this.promise ? await received : received;            // โœ…

// Register through the barrel in one call
expect.extend(matchers);                                            // โœ…

// Test the matcher's own pass and message
expect(result.pass).toBe(false);                                    // โœ…

// Declare the type on jest.Matchers
interface Matchers<R> { toBeWithinTolerance(e: number, t: number): R; } // โœ…

// Use the asymmetric form for composability
expect(order).toEqual({ payment: expect.validPayment({ ... }) });  // โœ…

โŒ Don’t Do This:

// Build the message eagerly
return { pass, message: `expected ${received} ...` };              // โŒ

// Ignore this.isNot
return { pass, message: () => `expected ... to be ...` };          // โŒ

// Compare a promise directly without awaiting
const pass = received.amount > 0; // received is a Promise        // โŒ

// Shadow a built-in matcher name
expect.extend({ toBe: myToBe });                                    // โŒ

// Skip the matcher's own tests
// (a broken matcher hides every assertion that uses it)           // โŒ

// Return a plain boolean instead of the object
return difference <= tolerance;                                     // โŒ

// Use the asymmetric form for a direct assertion only
expect(validPayment(...)).toBe(true); // defeats the purpose        // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Matcher not foundRegistration missingImport the setup file
Wrong failure textMessage built eagerlyReturn message: () => ...
.not message reads wrongthis.isNot ignoredBranch the message
Promise comparison failsReceived not awaitedawait received when this.promise
Type error at call siteMissing .d.tsAugment jest.Matchers
declare global ignoredFile is not a moduleAdd export {}
Asymmetric matcher undefinedNot on jest.ExpectAugment jest.Expect
Matcher replaces built-inName collisionUse a distinct name

Real-World Examples

1. Tolerance matcher

expect(result).toBeWithinTolerance(100.0, 0.01);

2. Valid payment asymmetric

expect(order).toEqual({ payment: expect.validPayment({ amount: 100.0, currency: "USD" }) });

3. Business-hours matcher

expect(timestamp).toBeBusinessHours({ start: 9, end: 17 });

4. Error-code matcher

expect(validation).toHaveErrorCode("INVALID_EMAIL");

5. Promise-aware matcher

await expect(fetchPayment()).resolves.toBeValidPayment({ amount: 100.0, currency: "USD" });

6. Negated assertion

expect(payment).not.toBeWithinTolerance(100.0, 0.01);

7. Barrel registration

import * as matchers from "../matchers";
expect.extend(matchers);

8. Matcher’s own test

expect(toBeWithinTolerance(100.02, 100.0, 0.01).pass).toBe(false);

9. Type augmentation

declare global { namespace jest { interface Matchers<R> { toBeWithinTolerance(e: number, t: number): R; } } }

10. Setup file config

module.exports = { setupFilesAfterEnv: ["<rootDir>/setup/jest.setup.ts"] };

Visual

The Matcher Call Flow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  expect(payment).toBeWithinTolerance(100.0, 0.01)           โ”‚
โ”‚                            โ”‚                                โ”‚
โ”‚                            โ–ผ                                โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚
โ”‚  โ”‚  toBeWithinTolerance(received, expected, tolerance)   โ”‚ โ”‚
โ”‚  โ”‚                                                       โ”‚ โ”‚
โ”‚  โ”‚    difference = |received - expected|                 โ”‚ โ”‚
โ”‚  โ”‚    pass = difference <= tolerance                     โ”‚ โ”‚
โ”‚  โ”‚                                                       โ”‚ โ”‚
โ”‚  โ”‚    return { pass, message: () => "..." }              โ”‚ โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚
โ”‚                            โ”‚                                โ”‚
โ”‚              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                  โ”‚
โ”‚              โ–ผ                           โ–ผ                  โ”‚
โ”‚        pass === true                pass === false          โ”‚
โ”‚        test continues               message() called        โ”‚
โ”‚                                     test fails with text    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Two Matcher Forms

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  MATCHER FORM                  ASYMMETRIC FORM              โ”‚
โ”‚                                                             โ”‚
โ”‚  expect(x).toBeSomething()     expect.something()           โ”‚
โ”‚                                                             โ”‚
โ”‚  used at the top level         used inside toEqual,         โ”‚
โ”‚  of an assertion               toHaveBeenCalledWith,        โ”‚
โ”‚                                arrayContaining              โ”‚
โ”‚                                                             โ”‚
โ”‚  returns { pass, message }     returns {                    โ”‚
โ”‚                                  asymmetricMatch(received), โ”‚
โ”‚                                  toString()                 โ”‚
โ”‚                                }                            โ”‚
โ”‚                                                             โ”‚
โ”‚  one assertion, one value      composable structural match  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Registration Chain

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  matchers/tolerance.ts                                      โ”‚
โ”‚    export function toBeWithinTolerance(...) { ... }         โ”‚
โ”‚                            โ”‚                                โ”‚
โ”‚                            โ–ผ                                โ”‚
โ”‚  matchers/index.ts                                          โ”‚
โ”‚    export { toBeWithinTolerance } from "./tolerance";       โ”‚
โ”‚                            โ”‚                                โ”‚
โ”‚                            โ–ผ                                โ”‚
โ”‚  setup/jest.setup.ts                                        โ”‚
โ”‚    import * as matchers from "../matchers";                 โ”‚
โ”‚    expect.extend(matchers);                                 โ”‚
โ”‚                            โ”‚                                โ”‚
โ”‚                            โ–ผ                                โ”‚
โ”‚  jest.config.js                                             โ”‚
โ”‚    setupFilesAfterEnv: ["<rootDir>/setup/jest.setup.ts"]    โ”‚
โ”‚                            โ”‚                                โ”‚
โ”‚                            โ–ผ                                โ”‚
โ”‚  every test file: expect(x).toBeWithinTolerance(...)        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Message Function Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  matcher runs                                               โ”‚
โ”‚       โ”‚                                                     โ”‚
โ”‚       โ–ผ                                                     โ”‚
โ”‚  returns { pass, message }                                  โ”‚
โ”‚       โ”‚                                                     โ”‚
โ”‚       โ”œโ”€โ”€โ”€ pass === true โ”€โ”€โ”€โ”€โ–บ message never called         โ”‚
โ”‚       โ”‚                        (lazy by design)             โ”‚
โ”‚       โ”‚                                                     โ”‚
โ”‚       โ””โ”€โ”€โ”€ pass === false โ”€โ”€โ”€โ–บ message() called             โ”‚
โ”‚                                โ”‚                            โ”‚
โ”‚                                โ–ผ                            โ”‚
โ”‚                          this.isNot ?                       โ”‚
โ”‚                            yes โ”€โ”€โ–บ "NOT" variant           โ”‚
โ”‚                            no  โ”€โ”€โ–บ positive variant        โ”‚
โ”‚                                โ”‚                            โ”‚
โ”‚                                โ–ผ                            โ”‚
โ”‚                          failure text shown to developer    โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Extension pointexpect.extend({ ... })
Matcher return{ pass: boolean, message: () => string }
Received valueFirst parameter of the matcher
Negation flagthis.isNot
Promise flagthis.promise ("resolves" / "rejects")
Asymmetric methodasymmetricMatch(received)
Asymmetric labeltoString()
Type augmentationjest.Matchers<R> and jest.Expect
Registration hooksetupFilesAfterEnv
Matcher testDirect call to the implementation

Key takeaways:

  • A matcher returns pass and a lazy message function. The message is called only on failure, and it is the part that makes the matcher worth writingโ€”it turns a boolean into a domain-specific explanation of what went wrong.
  • this.isNot and this.promise are the context flags. The negation flag changes the message wording, and the promise flag tells the matcher to await the received value before comparing it.
  • The asymmetric form is the composable form. expect.something() returns an object with asymmetricMatch and toString, which works inside toEqual, toHaveBeenCalledWith, and arrayContaining, making the matcher a first-class structural assertion.
  • The type augmentation is what makes the matcher usable in TypeScript. jest.Matchers<R> covers the matcher form, jest.Expect covers the static form, and the .d.ts file must be a module (export {}) for declare global to work.
  • The barrel-plus-setup registration is the maintainable structure. One file per matcher, a barrel that exports them, a single expect.extend(matchers) in the setup file, and a setupFilesAfterEnv entry in the Jest config.
  • A matcher needs its own tests. The matcher’s pass and message are the two things to assert, and a bug in either one silently corrupts every test that uses it.

Remember: A custom matcher is a domain assertion that reads like a built-in one. Write the matcher as a function that returns pass and a lazy message, branch the message on this.isNot and this.promise, register it through expect.extend in a setup file, and declare the type so TypeScript sees it. Write the asymmetric form when the assertion needs to compose inside a structural comparison, and test the matcher itself before trusting the tests that consume it.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!