skip to content

In Jest 30, how do the .resolves and .rejects modifiers work, and what must a test do with the assertion they produce?

level: middleimportance: must knowfreq 65%

answer

  1. unwrap first, then match
  2. fulfilled value versus rejection reason
  3. the chain is itself a promise
  4. Error reasons need toThrow

basics

~20 s

In Jest 30, .resolves unwraps a fulfilled value and .rejects unwraps a rejection reason so any matcher can check it, failing if the promise settles the other way. The chain is a promise, so the test must await or return it.

solid answer

~40 s

`expect(promise).resolves` waits for the promise and runs the chained matcher on the fulfilled value; `expect(promise).rejects` runs it on the rejection reason. If the promise settles the other way, the assertion fails with a message such as `Received promise resolved instead of rejected`. The whole chain returns a promise, so the test must `await` it inside an `async` test or `return` it; otherwise the test ends before the matcher runs. For a wrapper that rejects with an `Error`, check it with `rejects.toThrow('Server error 500')`, `rejects.toThrow(Error)` or `rejects.toBeInstanceOf(Error)`. `rejects.toMatch` only accepts a string reason and fails with a matcher error on an `Error` object. The alias `toThrowError` was removed in Jest 30; use `toThrow`.

code

javascript · 12 lines
javascript
const {fetchJson} = require('./fetchJson'); // rejects with Error(`Server error ${status}`) on a 5xx

const failing = async () => ({status: 500, body: null});

test('rejects on a 500 (awaited)', async () => {
  await expect(fetchJson(failing, '/users/7')).rejects.toThrow('Server error 500');
  await expect(fetchJson(failing, '/users/7')).rejects.toBeInstanceOf(Error);
});

test('rejects on a 500 (returned)', () => {
  return expect(fetchJson(failing, '/users/7')).rejects.toThrow(/500/);
});

go deeper

for a junior

Recall that resolves checks the fulfilled value, rejects checks the rejection reason, and either chain must be awaited or returned.

for a middle

Explain how each modifier fails when the promise settles the other way, and which matcher fits an Error reason versus a string reason.

for a senior

Prefer awaited rejects over try and catch in reviews, and spot an unawaited chain or a string matcher on an Error reason before it ships.

for a principal

Set the team's convention for asserting async errors so that every error branch test fails when the error stops happening.

## What the modifiers do Jest's `expect(value)` normally checks a value that already exists. A promise is different: the value you care about is not there yet, and it might never arrive because the promise rejects instead. The two **promise modifiers** bridge that gap: - **`.resolves`** waits for the promise to fulfil and hands the **fulfilled value** to the matcher that follows, so `await expect(fetchJson(get, url)).resolves.toEqual({id: 7})` checks the parsed body. - **`.rejects`** waits for the promise to reject and hands the **rejection reason** to the matcher that follows, so `await expect(fetchJson(failing, url)).rejects.toThrow('Server error 500')` checks the error. Any matcher can follow either modifier, including `.not`: `resolves.not.toBe('octopus')` is valid. The received value must be a promise; Jest's own matcher code also accepts a function that returns one and calls it, and reports a matcher error for anything else. ## When the promise settles the wrong way Each modifier is also an assertion about **how** the promise settles. If the wrong thing happens, the assertion fails before the chained matcher is consulted: | Written | Promise does | Result | |---|---|---| | `resolves.toEqual(body)` | fulfils with `body` | passes | | `resolves.toEqual(body)` | rejects | fails: `Received promise rejected instead of resolved` | | `rejects.toThrow('500')` | rejects with an error whose message contains `500` | passes | | `rejects.toThrow('500')` | fulfils | fails: `Received promise resolved instead of rejected` | That second half is why `.rejects` is safer than a `try` / `catch` around an awaited call: when the call unexpectedly succeeds, the modifier fails the test, while a `catch` block is simply skipped and the test passes with no assertion run. ## The assertion is a promise: await it or return it Because the modifier has to wait, `expect(promise).rejects.toThrow(...)` does not finish when the line executes. It **returns a promise** that settles once the matcher has run. Jest only waits for a promise the test function hands back, so the chain has to be: 1. **awaited** inside an `async` test: `await expect(p).rejects.toThrow('500')`, or 2. **returned** from a plain test: `return expect(p).rejects.toThrow('500')`. Without either, the test function returns before the assertion runs and Jest stops waiting. If the assertion then fails, its rejection belongs to no test; it may be reported late, surface as an unhandled error, or be lost. Several awaited chains can sit in one test, each on its own line. ## Matching an Error reason Most production code rejects with an `Error` object, and that decides which matcher fits: - **`rejects.toThrow('Server error 500')`** checks that the message contains the string; `toThrow(/500/)` uses a regular expression; `toThrow(Error)` checks the class. - **`rejects.toBeInstanceOf(Error)`** checks the class only. - **`rejects.toHaveProperty('message', 'Server error 500')`** checks one field exactly. - **`rejects.toMatch('500')`** works only when the reason is a **string**; given an `Error` it fails with `received value must be a string`. The documentation's `rejects.toMatch('error')` examples assume a promise that rejects with a plain string. - **`rejects.toThrowError(...)`** no longer exists: Jest 30 removed that alias, along with the other alias matchers, in favour of `toThrow`. ## Patterns that look right but are not - **`expect(() => fetchJson(failing, url)).toThrow()`** without a modifier: an `async` function never throws synchronously, it returns a rejected promise. Plain `toThrow` therefore fails with `Received function did not throw`, and the rejected promise is left with no handler. Use `.rejects` instead. - **A `try` block around an unawaited chain**: nothing in `try { expect(p).rejects.toThrow() } catch {}` throws synchronously, so the `catch` can never see the assertion's failure. - **Asserting twice on one promise** is fine: a promise settles once, and `await expect(p).rejects.toThrow('500')` followed by `await expect(p).rejects.toBeInstanceOf(Error)` both read the same settled reason without re-running the request. ## Choosing between the modifier and plain await `expect(await fetchJson(get, url)).toEqual(body)` also fails when the promise rejects, because `await` throws the rejection out of the test body. The difference is in the report: the modifier says that a promise rejected when it should have resolved and shows the reason, while the plain `await` surfaces the raw error as if the test itself had crashed. For the rejection path there is no plain-`await` equivalent short of `try` / `catch`, which is why `await expect(...).rejects` is the idiomatic way to test an error branch. The Jest documentation treats the styles as interchangeable and leaves the choice to readability.

  • Why does rejects.toMatch('500') fail when fetchJson rejects with new Error('Server error 500')?
    `toMatch` checks a string against a string or regular expression, and `.rejects` hands it the rejection reason, which here is an `Error` object. Jest reports a matcher error, `received value must be a string`. Use `rejects.toThrow('500')`, which reads the error's message, or `rejects.toHaveProperty('message', 'Server error 500')`.
  • What does expect(await p).toEqual(x) lose compared with await expect(p).resolves.toEqual(x)?
    Both fail when `p` rejects. With plain `await`, the rejection is thrown out of the test body and reported as the raw error. With `.resolves`, Jest reports an assertion failure that says the promise rejected instead of resolving and shows the reason, which reads more clearly in a failing run.

  • rejects.toMatch reads an Error's message the same way toThrow does.
  • expect(...).rejects is checked synchronously, so it needs no await or return.
  • If the promise fulfils, an expect(...).rejects assertion simply passes as a no-op.
  • The resolves and rejects modifiers only work with toBe and toEqual.
  • Jest 30 still accepts rejects.toThrowError for checking a rejected error.

Assumes Jest 30, which removed toThrowError and the other alias matchers; toThrow is the remaining name for checking a rejection's error.