Errors, Negative Paths and Failure Injection
Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.
What you will be able to do
#- Test that errors are thrown with the right type and message.
- Exercise negative paths instead of only the happy path.
- Inject failures to verify recovery and fallback behavior.
Overview
#Errors are behavior
How code fails is part of its contract. A function that throws a typed error with a useful message is easier to handle than one that returns undefined and lets the caller crash later. Tests should pin the error type and message the same way they pin return values.
function parseAge(input) {
const age = Number(input);
if (!Number.isInteger(age) || age < 0) {
throw new TypeError('age must be a non-negative integer');
}
return age;
}
Assert the throw, not just that something threw
A test that only checks assertThrows passes when the function throws for the wrong reason. Assert the error type and message so a future change that throws a different error fails the test. This is the difference between 'it threw' and 'it threw correctly'.
Negative paths
For every operation there is a failure path: invalid input, missing record, permission denied, network error. Each deserves a test. The happy path is usually the shortest and least interesting code; the error handling is where defects accumulate because it is rarely exercised.
Inject failures deliberately
To test recovery, make the dependency fail on purpose. A fake that rejects on the first call and resolves on the second tests retry. A fake that returns a 500 tests the error branch. A clock that jumps forward tests timeout handling. Failure injection is how you reach the branches that production rarely hits.
Do not swallow errors
A common defect is a catch block that logs and continues, hiding the failure. Test that a failure propagates or is converted into a user-visible error state, not silently ignored. A test that asserts the error state is visible will catch a future catch-and-ignore regression.
Clean up after failures too
Code that acquires a resource should release it on both the success and failure paths. Test the failure path and assert the resource was released. A leaked lock or connection on the error path is a production outage waiting to happen.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does `parseAge('-1')` do?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptfunction parseAge(input) { const age = Number(input); if (!Number.isInteger(age) || age < 0) { throw new TypeError('age must be a non-negative integer'); } return age; } console.log(parseAge('-1'));Exercise 2Explain
Explain why asserting only that a function throws is a weak test.
Reveal the reference answer
reference.javascriptAny throw satisfies the assertion, including a throw from a typo or an unrelated bug. The test passes even though the function failed for the wrong reason. Asserting the error type and message pins the intended failure, so a future change that throws a different error, or throws accidentally, fails the test. The contract is not just 'it throws' but 'it throws this'.The answer should distinguish any failure from the intended failure and connect the assertion to the error contract.
Exercise 3Implement
Implement `parseAge(input)` that throws a TypeError with message 'age must be a non-negative integer' for non-integer or negative input, and returns the number otherwise. `console.log(parseAge('30'))` should print `30`.
starter.javascriptfunction parseAge(input) { // your code here }Reveal the reference answer
reference.javascriptfunction parseAge(input) { const age = Number(input); if (!Number.isInteger(age) || age < 0) { throw new TypeError('age must be a non-negative integer'); } return age; }Authored expected output: 30
Number converts the string, Number.isInteger rejects NaN and decimals, and the negative check rejects values below zero. Valid input returns the number.
Exercise 4Debug
This catch block swallows the error and returns a value, hiding failures. Fix it to rethrow so callers see the error, so `load(failing)` prints `rejected`.
starter.javascriptasync function load(fetchImpl) { try { const res = await fetchImpl('/api/data'); return await res.json(); } catch (error) { return null; } } const failing = async () => ({ ok: false, status: 500, json: async () => ({}) }); load(failing).then(() => console.log('resolved')).catch(() => console.log('rejected'));Reveal the reference answer
reference.javascriptasync function load(fetchImpl) { try { const res = await fetchImpl('/api/data'); if (!res.ok) throw new Error('HTTP ' + res.status); return await res.json(); } catch (error) { throw error; } } const failing = async () => ({ ok: false, status: 500, json: async () => ({}) }); load(failing).then(() => console.log('resolved')).catch(() => console.log('rejected'));Authored expected output: rejected
Returning null on any error hides the failure from callers, who then treat null as a valid result. Rethrowing preserves the error so the caller can handle it. The explicit ok check also converts an HTTP error into a thrown error.
Exercise 5Test
Write tests that prove `parseAge` throws a TypeError for negative input and returns a number for valid input.
starter.javascriptfunction parseAge(input) { const age = Number(input); if (!Number.isInteger(age) || age < 0) { throw new TypeError('age must be a non-negative integer'); } return age; }Reveal the reference answer
reference.javascriptfunction assertEqual(actual, expected, label) { if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual); } let threw = null; try { parseAge('-1'); } catch (error) { threw = error; } assertEqual(threw instanceof TypeError, true, 'throws TypeError'); assertEqual(threw.message, 'age must be a non-negative integer', 'message'); assertEqual(parseAge('30'), 30, 'valid input'); console.log('parseAge verified');Authored expected output: parseAge verified
The test captures the thrown error and asserts both its type and message, which pins the contract. The final assertion covers the valid path so the test proves both outcomes.
Exercise 6Interview
In an interview, explain how you would test the failure path of a file upload.
Reveal the reference answer
reference.javascriptI inject a fake uploader that fails with each realistic error: a network rejection, a 413 too-large response and a 401 unauthorized. For each I assert the correct error state reaches the user and that any progress indicator resets. I assert the file handle or temporary resource is released on the failure path, not just the success path. I also test a retry that succeeds on the second attempt to verify recovery.The answer should cover multiple realistic failures, the user-visible state, resource cleanup on failure, and recovery.
Common misconceptions
#- Testing that something threw is enough.
- Error handling is defensive code that does not need tests.
- A catch block that logs the error is a complete failure handler.
Follow-up practice
#- testing-security-testing
- testing-integration
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.