How to Test Error and Edge Paths
Test the paths that are hard to reach: force each failure, cover boundaries and empty inputs, and assert the error shape and the cleanup.
On this page
Introduction
The happy path is easy to test and runs the most, so it is covered by default. The error and edge paths are where the bugs are: the handler that leaks a resource on a throw, the wrong status code for a missing resource, the empty list that the loop assumes is non-empty, the boundary that is off by one. These paths only run when the condition is forced, so unless the test forces it, the path is never exercised and its bug ships.
This tutorial covers enumerating the error paths, forcing each failure, asserting the error shape and the cleanup, and covering the boundaries. The examples use a stubbed dependency and boundary inputs, and the discipline applies to any code with error handling.
Enumerate the failure and edge cases
Before writing the tests, list what can go wrong and what is at the boundary. The failures: a dependency throws, a dependency times out, an input is invalid, a resource is missing, an operation is unauthorized, a duplicate is rejected. The edges: an empty collection, a single element, the maximum size, the zero value, the just-before and just-after of a limit. Each is a test case.
Derive the list from the code, not from the happy path. Read the try and catch blocks and check each one has a test that reaches it. Read each comparison and check its boundary. Read each resource acquisition and check the path where the acquisition fails or the work between acquisitions throws, which is where the cleanup matters.
Force each failure explicitly
A failure path is reached only when the condition occurs, so the test must force it. A stubbed dependency configured to throw reaches the catch block; an invalid input reaches the validation; a missing key reaches the not-found branch. The failure should be forced through a controllable seam, not by manipulating the environment, so the test is explicit and the path runs on demand.
Stubbing the dependency to throw is the general technique: the test provides a stub that fails on the call it wants to fail, and the code under test handles it. For a specific call order, a stub that fails on the first call and succeeds on the second tests a retry. Each forced failure should be a distinct test, so a failure names the exact condition it covers.
import { vi } from 'vitest';
it('returns 502 when the downstream fails', async () => {
const downstream = { get: vi.fn().mockRejectedValue(new Error('upstream down')) };
const handler = makeHandler(downstream);
const res = await handler({ id: 1 });
expect(res.status).toBe(502); // the error path's status
expect(res.body.error).toBe('upstream_error'); // the error shape
});
it('returns 404 when the resource is missing', async () => {
const downstream = { get: vi.fn().mockResolvedValue(null) };
const res = await makeHandler(downstream)({ id: 1 });
expect(res.status).toBe(404);
});
Assert the error shape and the cleanup
Assert what the caller sees on the error path: the status, the error code, the message shape. An error path that throws the expected exception but returns the wrong status is still a bug, so assert the observable outcome rather than only that an error was raised. This pins the contract the caller depends on, including the cases.
Assert the cleanup too. A handler that acquires a connection, throws, and does not release it leaks on every error, and a test that only checks the error misses it. Assert the resource count returns to zero after the failing call, and that a lock is released, so the failure path leaves nothing behind. This is where an untested error path leaks in production.
it('releases the connection even when the work throws', async () => {
const pool = makeCountingPool();
const handler = makeHandler(pool);
await expect(handler({ fail: true })).rejects.toThrow();
expect(pool.inUse).toBe(0); // the finally ran on the error path
});
Cover the boundaries and the empty case
Test the boundary values where an off-by-one hides: zero, one, the maximum, one past the maximum, and the exact limit. For a pagination, test the last page and one past it. For a slice, test an empty range and a range that ends at the last element. Each boundary test states the intended behavior, so an inclusive-versus-exclusive bug is caught.
Test the empty collection and the single element, because loops and aggregations often assume at least one item. An empty list that a reduce iterates without a seed throws; a single-element list can hide an off-by-one in a look-ahead. These are the cases the happy path with several elements never reaches, and they are common in production data.
# boundary cases as a table: each row states the intended behavior
node -e '
const cases = [[0, 0], [1, 1], [10, 10], [11, 10]]; // input, expected capped value
for (const [input, expected] of cases) {
const got = clamp(input, 0, 10);
if (got !== expected) throw new Error(input + " -> " + got + " expected " + expected);
}
console.log("boundaries ok");
'
Test the error path does not swallow
A catch block that logs and returns a success hides the error, so test that a failure on a path the caller must know about is not swallowed. Inject the failure, assert the caller receives an error rather than a default, and assert the failure is metered or logged so it is observable. A swallowed error is a silent data-loss or a wrong-success bug.
Where the code intentionally degrades, such as serving a default when a cache is down, test that the degradation happens and that it is observable, so the degraded path is a decision rather than an accident. The test states which failures are fatal and which are degraded, and the code matches it.
Common pitfalls
Testing only the happy path so the error paths are never exercised, forcing a failure by manipulating the environment instead of a stub, asserting an exception was thrown without checking the status the caller sees, not asserting the resource cleanup on the error path, and skipping the empty and boundary cases are the recurring mistakes. An enumerated error list, stubbed failures, error-shape and cleanup assertions, and boundary cases address them.
Conclusion
Error and edge paths are where the bugs and the leaks are, and they run only when forced. Enumerate the failures and boundaries, force each with a stub or an input, assert the error shape the caller sees and the cleanup, and cover the empty and boundary cases. Self-check by asserting a failing dependency yields the right status and leaves no resource held. Then the code is tested on the paths that fail in production, not just the one that works.
Sources: Google Testing Blog: Test behaviour, not implementation, xUnit Patterns: Exception testing, OWASP: Error handling cheat sheet.
FAQ
- Why are error paths often untested?
- The happy path is easy to exercise and the error paths require forcing a condition, so they are skipped unless deliberately tested. But error paths are where the resources leak and the wrong status returns, so they are the ones that fail in production.
- How do I force a failure?
- Inject a dependency that throws, pass an invalid input, or use a stub configured to fail. The path should be reachable without playing with the environment, so the failure is explicit in the test and the path runs on demand.
Report a problem with this articleOpens a pre-filled issue on GitHub.