A Jest 30 custom matcher registered with expect.extend works in one file, prints a wrong message under .not, and is not a function in other files. Why?
answer
- one message, two directions
- what pass means under .not
- a regular function, not an arrow
- registered per test file
- a setup module every file loads
basics
~20 sA matcher returns { pass, message }, and under .not Jest fails when pass is true, so message must describe that case too, typically via this.isNot. expect.extend registers only in the calling file; move it into a setupFilesAfterEnv module.
solid answer
~40 s`expect.extend({ toBeValidCents(received) { ... } })` adds a matcher that receives the value passed to `expect`, then the matcher's own arguments, and returns `{ pass, message }`, where `message` is a no-argument function. Jest, not the matcher, applies `.not`: a plain call fails when `pass` is `false`, a `.not` call fails when `pass` is `true`, and both print `message()`. A message hard-coded as *expected X to be valid* reads backwards under `.not`; branch on `pass` or `this.isNot`. Write it as a regular `function`, because `this` carries `isNot`, `utils`, `equals` and `customTesters`, and an arrow function loses that context. Finally, each test file has its own `expect`, so registration in one file never reaches another: put the call in a module listed in `setupFilesAfterEnv`, plus a `declare module 'expect'` block for TypeScript.
code
javascript · 13 lines// test/matchers.js, listed in setupFilesAfterEnv
expect.extend({
toBeValidCents(received) {
const pass = Number.isInteger(received) && received >= 0;
return {
pass,
message: () =>
`expected ${this.utils.printReceived(received)} ${
this.isNot ? 'not ' : ''
}to be a non-negative whole number of cents`,
};
},
});go deeper
Know that expect.extend adds a matcher returning an object with pass and message, called just like a built-in matcher.
Explain how Jest applies .not to the pass flag, why message is a function, and what this.isNot and this.utils provide.
Diagnose a misbehaving custom matcher from its symptoms: backwards .not messages, a missing this from an arrow function, and per-file registration fixed with a setupFilesAfterEnv module.
Decide which domain assertions earn a shared custom matcher, since each becomes team vocabulary that must keep clear messages and typed declarations as the suite grows.
## The contract of a custom matcher `expect.extend(matchers)` adds methods to `expect`. Each matcher is a function called with the value given to `expect(received)` followed by the arguments given to the matcher, so `expect(999).toBeWithin(0, 1000)` calls `toBeWithin(999, 0, 1000)`. It must return an object with: - **`pass`**: a boolean saying whether the received value matched. - **`message`**: a function with no arguments that returns the failure text. It is a function so the text is only built when an assertion actually fails. A matcher may also **throw** when its inputs make no sense, for example a `TypeError` when a range matcher is handed a string. That reports a misuse of the matcher rather than a failed assertion, and the docs' own range example does exactly this. Jest validates the result. A matcher that returns a bare boolean throws *Unexpected return from a matcher function*, explaining that matchers should return `{message?: string | function, pass: boolean}`. A matcher may also be `async`; it then returns a promise, and the call site must `await expect(value).toMatchSomething()`, or the test can finish before the result is checked. ## How .not is applied The matcher reports a fact; Jest decides the outcome: | Call | `pass` returned | Outcome | |---|---|---| | `expect(x).toBeValidCents()` | `true` | passes | | `expect(x).toBeValidCents()` | `false` | fails and prints `message()` | | `expect(x).not.toBeValidCents()` | `true` | fails and prints `message()` | | `expect(x).not.toBeValidCents()` | `false` | passes | So `message` is printed in **two** different failure situations, and one fixed sentence cannot describe both. The docs' pattern returns a different message depending on `pass`; the alternative is to read `this.isNot` and insert a *not*. A matcher whose message ignores both prints *expected 5 to be positive* when the real failure was that 5 was positive and the test said `.not`. ## What this gives you Inside a matcher written as a regular function, `this` is the **matcher context**: - `this.isNot`: `true` when the call used `.not`. - `this.promise`: `'resolves'`, `'rejects'` or an empty string, for accurate hints when chained after those modifiers. - `this.equals(a, b, customTesters?)`: Jest's own recursive equality, which honours asymmetric matchers. - `this.customTesters`: the equality testers registered with `expect.addEqualityTesters`, to pass along to `this.equals`. - `this.utils`: formatting helpers such as `printReceived`, `printExpected` and `matcherHint`. - `this.expand`: whether the run asked for full diffs. An **arrow function** does not receive this context; it keeps the `this` of the scope where it was written, so `this.utils.printReceived(...)` throws a `TypeError` the first time the message is built, and `this.isNot` is never set. ## Why other files cannot see it Each Jest test file runs in its own environment with its own module registry and its own `expect`. Calling `expect.extend` inside one test file registers the matcher for that file only; another file calling it fails with `TypeError: expect(...).toBeValidCents is not a function`. The documented fix is to move the call into a module listed in the `setupFilesAfterEnv` configuration key, which Jest loads into every test file's environment before its tests; that key itself is covered with Jest configuration. For TypeScript, a `declare module 'expect'` block that extends the `Matchers<R>` and `AsymmetricMatchers` interfaces gives the new method types and autocompletion. ## What registration buys Once registered, a matcher is more than a method: - It works as an **asymmetric matcher**: `expect.toBeValidCents()` and `expect.not.toBeValidCents()` can sit inside `toEqual`. - It can be chained after `.resolves` and `.rejects`, with `this.promise` set accordingly. - Its failures print through the same reporter as built-in matchers, so a clear message matters. ## A diagnosis checklist 1. Does the matcher return an object with a boolean `pass`, not a bare boolean? 2. Is `message` a function, and does its text read correctly both with and without `.not`? 3. Is the matcher a regular function, so `this.utils` and `this.isNot` exist? 4. Is `expect.extend` called from a `setupFilesAfterEnv` module rather than one test file? 5. For an async matcher, is every call site awaited?
- What should a custom matcher use when it needs a deep comparison, for example against an expected line item?Use `this.equals(received, expected, this.customTesters)` rather than a hand-written comparison or a JSON string compare. It applies Jest's own recursive equality, honours asymmetric matchers inside the expected value, and respects any equality testers the project registered with `expect.addEqualityTesters`.
- How does an async custom matcher change the call site?An `async` matcher returns a promise, so the assertion itself returns a promise and the test must `await expect(value).toMatchRemote()`. Without the `await`, the test can finish and be reported as passed before the matcher's result is checked.
- A custom matcher should return true or false, like a predicate.
- Under .not, Jest negates the message for you, so one wording is enough.
- Arrow functions work the same as regular functions inside expect.extend.
- Calling expect.extend in one test file makes the matcher available to the whole run.
- A custom matcher cannot be used inside toEqual as an asymmetric matcher.