In Jest 30, why does toThrow need the call wrapped in a function, and what arguments narrow the expected error?
answer
- who gets to catch the error
- pass a function, not a result
- string, regex, class or error
- the alias that was removed
basics
~20 stoThrow has to call the code itself to catch the error; an unwrapped call throws before expect even runs. Pass a substring, a regex, an error class (instanceof) or an error object (equal message) to narrow the match.
solid answer
~40 s`expect(fn).toThrow()` calls `fn` inside a `try` and inspects what it catches. Write `expect(parsePrice('abc')).toThrow()` and JavaScript evaluates `parsePrice('abc')` first: if it throws, the error escapes before `expect` is even called and the test fails with that raw error; if it returns, the matcher receives a number and fails with *received value must be a function*. So wrap it: `expect(() => parsePrice('abc')).toThrow(...)`. The argument narrows the check: a string must be a **substring** of the message, a regex must **match** it, a class must pass **instanceof** (so `Error` also matches every subclass), and an error object must have an **equal** message. Jest 30 removed the `toThrowError` alias, so `toThrow` is the only name; `.not.toThrow()` asserts that the call completes.
code
javascript · 23 linesclass ParseError extends Error {
constructor(message) {
super(message);
this.name = 'ParseError';
}
}
function parsePrice(text) {
if (!/^\d+(\.\d{1,2})?$/.test(text)) {
throw new ParseError(`invalid price: ${text}`);
}
return Number(text);
}
test('parsePrice rejects malformed input', () => {
const parseBad = () => parsePrice('12,50');
expect(parseBad).toThrow(); // anything thrown
expect(parseBad).toThrow('invalid price'); // substring of the message
expect(parseBad).toThrow(/^invalid price: 12,50$/); // whole message, anchored
expect(parseBad).toThrow(ParseError); // instanceof
expect(() => parsePrice('12.50')).not.toThrow();
});go deeper
Remember to hand expect a function when using toThrow, and know the four argument forms: substring, regex, error class and error object.
Explain why argument evaluation order breaks an unwrapped call, what each argument form compares, and that Jest 30 dropped the toThrowError alias.
Write throw assertions that cannot pass by accident: a specific class plus an anchored message beats toThrow() or toThrow(Error), which also pass on an unrelated bug.
Treat a Jest 30 upgrade's alias removals as a mechanical rename, and use the pass to tighten loose toThrow() assertions the rename touches anyway.
## What toThrow actually does Most matchers inspect a **value**. `toThrow` inspects a **behaviour**: whether calling something throws. To observe that, the matcher has to be the one making the call. It receives a function, invokes it inside a `try`, and examines the caught error, or notes that nothing was thrown. That is why the code under test must be **wrapped**: `expect(() => parsePrice('abc')).toThrow()`. The arrow function delays the call until the matcher is ready to catch it. Passing a named function reference, such as `expect(parseBad).toThrow()` where `parseBad` is `() => parsePrice('abc')`, works the same way. ## How an unwrapped call goes wrong JavaScript evaluates the argument of `expect(...)` before `expect` runs. With `expect(parsePrice('abc')).toThrow()`, the parser is called first, and there are two outcomes, neither of them a meaningful assertion: 1. **The parser throws.** The error propagates out of the test body before `expect` or `toThrow` ever execute. The test fails, but the report shows the raw `ParseError` and a stack pointing into the parser, not a matcher message. It looks like a bug in the code when it is a bug in the test. 2. **The parser returns.** `toThrow` receives the returned number, not a function, and fails with a matcher error: *received value must be a function*, followed by the received type and value. Either way the test can never pass, which is at least loud. The real danger is the opposite mistake, an assertion too loose to fail, covered below. ## Reading a toThrow failure When the wrapped call is set up correctly, the failure output tells you which half of the check failed. If nothing was thrown, it says *Received function did not throw*. If the wrong kind of error was thrown for a class argument, it prints the *Expected constructor* and the *Received constructor* side by side, followed by the received message. For a string or an error-object argument it prints the expected substring or message next to the received message. Reading these lines first usually tells you whether the code or the assertion is wrong. ## Narrowing the expected error With no argument, `toThrow()` passes if anything at all is thrown. The optional argument narrows that: | Argument | What must hold | Example | |---|---|---| | none | something was thrown | `toThrow()` | | string | the message **includes** the substring | `toThrow('invalid price')` | | regular expression | the message **matches** the pattern | `toThrow(/^invalid price: 12,50$/)` | | error class | the thrown value is an **instance of** the class | `toThrow(ParseError)` | | error object | the message **equals** the object's message | `toThrow(new Error('invalid price: 12,50'))` | | asymmetric matcher | the thrown value matches it | `toThrow(expect.objectContaining({ code: 'E_PRICE' }))` | The details that trip people up: - A **string is a substring check**, not an exact match. For the whole message, use an anchored regex such as `/^invalid price: 12,50$/`. - A **class is an `instanceof` check**, so `toThrow(Error)` passes for every subclass, including a `TypeError` raised by an unrelated bug inside the parser. Name the specific class. - An **error object** needs an equal message: `toThrow(new Error('invalid price'))` fails against `invalid price: 12,50`. - `.not.toThrow()` asserts that the call completes without throwing. - A rejected promise is asserted by awaiting `.rejects.toThrow(...)`, which belongs with asynchronous testing rather than here. ## Jest 30: one name for it Earlier releases also accepted `toThrowError`, an alias deprecated since Jest 26. Jest 30 removed it along with the other alias matchers, so a suite that still calls it fails with `TypeError: expect(...).toThrowError is not a function`. The fix is a rename to `toThrow`; the arguments and behaviour are identical. Note that `toThrowErrorMatchingSnapshot` and `toThrowErrorMatchingInlineSnapshot` still exist: they are snapshot matchers, not aliases, and are covered with snapshot testing. ## A checklist for throw assertions 1. Pass a function: an arrow wrapper or a reference to a zero-argument function. 2. Name the specific error class rather than `Error`. 3. Add the message, as a substring or an anchored regex, when the text is part of the contract. 4. Use `.not.toThrow()` for the happy path rather than relying on the absence of a failure. 5. After a Jest 30 upgrade, replace any `toThrowError` with `toThrow`.
- Does `toThrow(Error)` prove that the parser threw its own error type?No. A class argument is an `instanceof` check, so `toThrow(Error)` passes for every subclass, including a `TypeError` from an unrelated bug inside the parser. Pass the specific class, `toThrow(ParseError)`, and when the text is part of the contract add an anchored regex such as `/^invalid price: /`.
- How do you assert a property other than the message, such as a `code` field on the thrown error?Pass an asymmetric matcher: `toThrow(expect.objectContaining({ code: 'E_PRICE' }))` checks the thrown value against it. The alternative is to catch the error in a `try`/`catch` and assert on it directly, guarded with `expect.assertions(1)` so the test fails if nothing was thrown.
- expect(parsePrice('bad')).toThrow() works because Jest catches the error for you.
- toThrow('invalid') requires the message to be exactly 'invalid'.
- toThrow(Error) fails when the code throws a subclass such as TypeError.
- toThrowError is still the Jest 30 matcher for checking an error message.
- toThrow(new Error('invalid')) passes when the message merely contains 'invalid'.
Assumes Jest 30, which removed the toThrowError alias (deprecated since Jest 26); toThrow is now the only name and behaves identically.