test('throws for missing user', async () => {
expect.assertions(1);
try {
await service.findOne(999);
} catch (e) {
expect(e).toBeInstanceOf(NotFoundException);
}
});
expect.assertions(n) makes the test fail unless exactly n assertions ran during it. expect.hasAssertions() requires at least one. Both protect you from tests that silently skip their checks.
This matters when assertions sit in code that may not run:
- a
catchblock - a callback
- a
.then()
In this test, if findOne resolves, the catch never runs. Without the guard, the test passes with zero assertions. With the guard, the test fails and says one assertion was expected but none were called.
The cleaner fix is usually to avoid this pattern. Write await expect(service.findOne(999)).rejects.toThrow(NotFoundException). It fails by itself if the promise resolves. Keep expect.assertions for callback or event-driven code that you can't write as a single awaited assertion.
- It fails the test unless the expected number of assertions ran.
- It protects assertions inside catch blocks and callbacks.
- Without it, a promise that resolves by mistake gives a test with zero assertions that still passes.
- Prefer await expect(...).rejects where possible.
Read more