Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 30 ยท Matchers

Errors and Custom Matchers

Test thrown errors with Jest toThrow, wrap calls correctly, and write your own matchers with expect.extend and clear failure messages. Runnable stand-in.

Good code fails loudly and on purpose: a function rejects a negative quantity, a parser refuses broken input, a service throws when it is misconfigured. Those failures are behavior, so they deserve tests as much as the happy path does. Jest checks them with toThrow.

Once your suite grows you will also notice the same multi-line check repeated in many tests, such as "this value is a valid email" or "this number is within a range". Jest lets you give that check a name with expect.extend, so tests read like sentences and failures explain themselves. This lesson covers both, and it assumes you know the basics from Common Matchers and Arrays and Objects.

Real versus stand-in. Jest code in plain blocks is real and read-only, because the site cannot run Jest. The runnable examples use a small expect that supports toThrow and expect.extend, written for this lesson. It shows how the mechanism works but is not Jest's source, and Jest's messages are more detailed.

Four ways to describe an error

No argument It threw something.
String or regex The message contains it.
Error class The error is an instance of it.
Error object The message equals it exactly.

All four are arguments to toThrow.

1 / 2

Testing that code throws

Suppose we have this function:

JavaScript
function parseQuantity(text) {
  const n = Number(text);
  if (!Number.isInteger(n)) {
    throw new TypeError(`Quantity must be a whole number, got "${text}"`);
  }
  if (n < 1) {
    throw new RangeError('Quantity must be at least 1');
  }
  return n;
}

The trap is writing expect(parseQuantity('abc')).toThrow(). JavaScript evaluates the argument first, so the error is thrown before expect ever sees it, and the test crashes with that raw error instead of passing. Wrap the call in a function so that Jest calls it inside its own try/catch:

JavaScript
expect(() => parseQuantity('abc')).toThrow();      // correct
expect(parseQuantity('abc')).toThrow();            // wrong: throws too early

You can wrap with an arrow function, or pass a bound function such as parseQuantity.bind(null, 'abc').

The toThrow variants

JavaScript
expect(() => parseQuantity('abc')).toThrow();                         // anything
expect(() => parseQuantity('abc')).toThrow('whole number');           // message contains
expect(() => parseQuantity('abc')).toThrow(/whole number/);           // message matches
expect(() => parseQuantity('abc')).toThrow(TypeError);                // instance of class
expect(() => parseQuantity('0')).toThrow(RangeError);
expect(() => parseQuantity('0')).toThrow(new RangeError('Quantity must be at least 1')); // same message
expect(() => parseQuantity('5')).not.toThrow();

Know the differences, because they decide how strict the test is:

  • A string checks that the error message contains that text, so it survives small wording changes outside the part you named.
  • A regular expression gives more control, for example case-insensitivity.
  • A class checks instanceof, ignoring the message. It is the sturdiest choice when callers rely on the error type.
  • An error object compares only the message, and it must be equal. It does not compare the class.

Combine class and message in two assertions when both matter, or inspect the error yourself:

JavaScript
let caught;
try {
  parseQuantity('abc');
} catch (error) {
  caught = error;
}
expect(caught).toBeInstanceOf(TypeError);
expect(caught).toHaveProperty('message', expect.stringContaining('whole number'));

Prefer this form when the error carries extra fields, such as an HTTP status or an error code.

Async errors

A rejected promise is not a thrown exception, so the wrapper function is not needed. Use rejects and await the whole assertion:

JavaScript
await expect(loadUser(0)).rejects.toThrow('not found');
await expect(loadUser(0)).rejects.toBeInstanceOf(NotFoundError);

Forgetting the await is a classic mistake that makes the test pass without checking anything. Testing Promises and Async/Await covers it in detail.

Why write a custom matcher?

Compare these two assertions:

JavaScript
expect(score >= 0 && score <= 100).toBe(true);
expect(score).toBeWithinRange(0, 100);

If the first one fails, Jest reports expected true, received false, which tells you nothing. The second can say expected 130 to be within range 0 - 100. A custom matcher also removes repeated logic and gives your domain its own vocabulary.

expect.extend

expect.extend takes an object of matcher functions. Each receives the value from expect(...) as its first argument, followed by whatever arguments the test passes. It returns an object:

  • pass: whether the check succeeded, as if there were no .not.
  • message: a function returning the failure text. It is a function so the string is built only when needed.
JavaScript
expect.extend({
  toBeWithinRange(received, floor, ceiling) {
    const pass = typeof received === 'number' && received >= floor && received <= ceiling;
    return {
      pass,
      message: () => pass
        ? `expected ${this.utils.printReceived(received)} not to be within ${floor} - ${ceiling}`
        : `expected ${this.utils.printReceived(received)} to be within ${floor} - ${ceiling}`,
    };
  },
});

Why does message depend on pass? Jest uses the same matcher for .not. When the test is expect(5).not.toBeWithinRange(1, 10) and pass is true, Jest treats that as a failure and shows your message, so the message must describe the negated situation. Inside a matcher, this.isNot tells you if .not was used, and this.utils offers helpers such as printReceived, printExpected and matcherHint.

Put the call to expect.extend in a setup file listed in the setupFilesAfterEnv option so every test file gets the matcher (configuration is in Configuring Jest). In TypeScript you also declare the new matcher's type so the compiler knows it exists. For most teams, a handful of well-chosen matchers beats dozens of one-off ones; if a check is used only once, an ordinary assertion is clearer.

A stand-in that shows the mechanism

This version of expect implements toThrow with the same argument rules and supports expect.extend, including .not and this.isNot. Run it and read each result against the rules above. Several lines are meant to fail, so you can see the messages.

Node.js toThrow rules and expect.extend, from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The two groups of results teach different things. In the first, toThrow(RangeError) fails when a TypeError was thrown, and toThrow() fails when nothing was thrown, with a message that says what happened. In the second, the custom matcher gives readable messages, and the last check shows .not flipping the meaning: pass is true, so the negated assertion fails and the negated message is used.

Sharing a matcher across tests

Custom matchers can build on each other and on ordinary values. This second example creates a matcher for a domain rule, "a valid order id looks like A- followed by digits", and then checks an error that carries an HTTP status by catching it.

Node.js A domain matcher with a helpful message

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last lines show the manual try/catch approach: when an error has extra fields such as status, catch it and assert on each field, rather than squeezing everything into toThrow.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does expect(parseQuantity('abc')).toThrow() crash the test instead of passing?

    Arguments are evaluated first. Wrap the call in a function, expect(() => parseQuantity('abc')).toThrow(), so Jest runs it and catches the error.
  2. 2. What does expect(fn).toThrow('whole number') check?

    A string argument means the message must include that substring. To require an exact message, pass an error object such as new Error('...').
  3. 3. What must a custom matcher return?

    pass tells Jest whether the check succeeded, and message is a function that lazily builds the failure text.
  4. 4. For expect(5).not.toBeWithinRange(1, 10), what is pass inside the matcher, and what happens?

    pass always describes the positive check. Because 5 is in range, pass is true, and with .not Jest treats that as a failure, so the message should describe the negated case.
  5. 5. How should you assert on a rejected promise?

    A rejection is not a synchronous throw, so use rejects and await the assertion. Awaiting the promise yourself would throw before expect runs.

Summary

  • Wrap the throwing call in a function: expect(() => fn()).toThrow().
  • toThrow accepts nothing, a message substring, a regex, an error class, or an error object (exact message).
  • For errors with extra fields, catch the error and assert on its properties.
  • Use await expect(promise).rejects.toThrow(...) for rejections.
  • expect.extend adds matchers that return { pass, message }; pass ignores .not, and message is a function that should describe the situation .not would create.
  • Create custom matchers for checks you repeat, and keep their failure messages specific.

Next: Testing Promises and Async/Await.