A Jest 30 test of a fetch wrapper's 500 branch asserts inside a catch block, yet passes when the wrapper succeeds. Why, and how do expect.assertions and expect.hasAssertions catch it?
answer
- zero assertions is still a pass
- the catch block is skipped
- count assertions at test end
- exact count versus at least one
basics
~20 sWhen the wrapper succeeds, the catch block never runs, no assertion executes, and Jest passes a test that ran no assertions. expect.assertions(n) fails it unless exactly n assertions ran; expect.hasAssertions() fails it unless at least one did.
solid answer
~40 sJest does not fail a test for running zero assertions. In `try { await fetchJson(ok) } catch (error) { expect(error.message).toMatch('500') }`, a successful call skips the `catch`, nothing throws, and the test passes whatever the 500 branch does. `expect.assertions(1)` at the top records how many assertions must run; when the test finishes, Jest compares the count and fails with `Expected one assertion to be called but received zero assertion calls.` It is an exact count, so two assertions also fail it. `expect.hasAssertions()` only requires at least one. Only assertions that run before the test ends are counted. The cleaner fix for this test is `await expect(fetchJson(failing)).rejects.toThrow('500')`, which fails by itself when the promise fulfils; keep the count guards for assertions that must live inside callbacks.
code
javascript · 22 linesconst {fetchJson} = require('./fetchJson'); // rejects with Error(`Server error ${status}`) on a 5xx
const ok = async () => ({status: 200, body: {id: 7}});
// Passes although the 500 branch never ran: the catch block is skipped
test('surfaces a 500 (unguarded)', async () => {
try {
await fetchJson(ok, '/users/7');
} catch (error) {
expect(error.message).toMatch('500');
}
});
// Fails, because zero assertions ran where one was required
test('surfaces a 500 (guarded)', async () => {
expect.assertions(1);
try {
await fetchJson(ok, '/users/7');
} catch (error) {
expect(error.message).toMatch('500');
}
});go deeper
Recall that an assertion inside a catch block only runs when the call fails, and that Jest passes a test with no assertions.
Explain how expect.assertions counts every matcher call and checks the exact number at test end, and how hasAssertions differs.
Diagnose a green test over a broken branch, rewrite it with awaited rejects, and keep count guards for callback-only assertions.
Decide whether a team enforces assertion guards suite-wide, weighing caught vacuous tests against counts that must be maintained.
## Why the test passes A Jest test fails for one of a small number of reasons: something it runs throws, a promise it returns rejects, or it exceeds its timeout. **Running zero assertions is not one of them** by default. Consider a test written to cover a fetch wrapper's server-error branch: ```js test('surfaces a 500', async () => { try { await fetchJson(get, '/users/7'); } catch (error) { expect(error.message).toMatch('500'); } }); ``` If `get` returns a 500, `fetchJson` rejects, the `catch` block runs, and the assertion checks the message. If someone breaks the wrapper so that it returns the body of a 500 instead of throwing, `await` succeeds, the `catch` block is **skipped**, nothing throws, and the test passes. The same shape appears with `.catch(error => expect(...))` on a returned promise, and with assertions inside callbacks that are never called. The test is green precisely when the behaviour it was written for has disappeared. ## Assertion-count guards Jest keeps a per-test count of **assertion calls**: every matcher that runs, including the matcher at the end of a `.resolves` or `.rejects` chain, adds one. Two functions turn that count into a check made when the test finishes: | Guard | Passes when | Failure message | |---|---|---| | `expect.assertions(1)` | exactly one assertion ran | `Expected one assertion to be called but received zero assertion calls.` | | `expect.assertions(2)` | exactly two assertions ran | names the expected and received counts | | `expect.hasAssertions()` | one or more assertions ran | `Expected at least one assertion to be called but received none.` | Points that trip people up: - `expect.assertions(n)` is **exact**. With `expect.assertions(1)` and two `expect` calls in the `catch` block, Jest fails the test with `Expected one assertion to be called but received two assertion calls.` Update the number when you add an assertion. - The count is checked when the test **finishes**, so an assertion that only runs after that point is not counted: a missing `await` on a slow promise then shows up as a count failure instead of a silent pass. A promise that settles within a few microtasks can still be counted in time, so the guard never replaces the `await`. - Both guards work in every async style: an `async` test, a returned promise or a `done` callback. They apply to the test that is running when they are called. - `expect.hasAssertions()` is the lighter guard: it cannot tell one assertion from three, but it does not need editing when assertions are added. Called in a `beforeEach`, it applies to every test in its scope. ## Fixing the test itself A guard makes the bad test fail; often the better move is to write a test that cannot pass vacuously in the first place: 1. Replace `try` / `catch` around an awaited call with **`await expect(fetchJson(get, url)).rejects.toThrow('Server error 500')`**. The `.rejects` modifier fails with `Received promise resolved instead of rejected` when the call succeeds, so no count is needed. 2. Keep `expect.assertions(n)` for code where the assertion **has** to sit inside a callback: a function that calls two callbacks in an unknown order, an event handler, a `.catch` on a returned promise. 3. Run the test once against **deliberately broken code**, for example by making the 500 path return normally. A test that stays green under that change is not testing the branch. ## Diagnosing a suite with this problem When a production bug lands in a branch whose test has always been green, these are the usual culprits, in rough order of frequency: - an assertion in a `catch` block or `.catch` callback with no count guard; - an assertion inside a `then` callback whose promise the test neither returned nor awaited; - an `expect(...).resolves` or `.rejects` chain that was never awaited; - a callback passed to the code under test that the code never calls, so its assertions never run. Coverage reports help a little here: a `catch` block that no test ever entered shows up as an uncovered branch, but a branch that *was* entered by some other test hides the problem, so coverage alone does not find vacuous tests. Searching the test files for `catch (` and `.catch(` near `expect`, and for `expect(` lines inside callbacks with no `expect.assertions` above them, finds most of them. Adding `expect.hasAssertions()` to a shared `beforeEach` is a cheap way to surface the zero-assertion tests across a whole file before rewriting them one by one.
- Does an awaited .rejects chain count toward expect.assertions in Jest?Yes. The matcher at the end of the chain is an assertion call, so `expect.assertions(1)` followed by `await expect(p).rejects.toThrow('500')` passes. It also means the count guard adds little there, because `.rejects` already fails when the promise fulfils.
- Why might a team prefer expect.hasAssertions() in a beforeEach over expect.assertions(n) in each test?`hasAssertions` catches the dangerous case, zero assertions, without a number to keep in sync as tests change, and a single `beforeEach` covers every test in its scope. The trade-off is that it cannot catch a test where one of two expected callback assertions silently stopped running.
- Jest fails any test that finishes without running an assertion.
- expect.assertions(1) means at least one assertion, so extra ones are fine.
- A green async test proves its error branch was exercised.
- expect.assertions makes Jest wait for promises the test did not await.
- A try and catch around the awaited call is as safe as rejects.