Library tests need collaborators that misbehave in specific ways. A mapper may throw synchronously before returning a promise, return a rejected promise, ignore cancellation temporarily, or reject with undefined. A source iterator may throw from next. Its return cleanup may also throw.
A useful test identifies the public outcome and the work that must not happen afterward. The task pool wraps mapper failure with index and cause, preserves source errors, preserves external abort reasons, and does not let a cleanup failure replace an existing primary failure.
Be careful with try/catch tests: throwing an assertion inside the same try block can make a broken operation appear to have thrown correctly. Keep the assertion after the catch, or use a dedicated assertion helper. In the example, didThrow reports whether the operation failed, including when the thrown value is undefined.
Predict, run, and explain
Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.
async function main() {
function didThrow(work) {
try {
work();
return false;
} catch {
return true;
}
}
console.log(
didThrow(() => {
throw undefined;
})
);
console.log(didThrow(() => 1));
}
main();Check your prediction
true
falseDistinguish call-time throws from promise rejection
An async boundary can fail while invoking a collaborator or while awaiting what it returned. Keep both operations inside the intended try/catch. A test that only returns a rejected promise misses a synchronous throw before any promise is produced.
Cleanup can also fail. Decide whether a secondary cleanup error replaces the primary outcome; this pool preserves an existing primary failure. Test identity, not merely a similar error message, to demonstrate that preservation.
async function main() {
async function outcome(work) {
try {
await work();
return "ok";
} catch {
return "failed";
}
}
console.log(
await outcome(() => {
throw "sync";
})
);
console.log(await outcome(() => Promise.reject("async")));
console.log(await outcome(() => Promise.resolve(0)));
}
main();Check your prediction
failed
failed
okThe same adapter sees both failure paths and preserves a fulfilled zero as success. Removing await would lose the asynchronous rejection path.
const primary = new Error("mapper");
const cleanup = new Error("cleanup");
let failure = primary;
try {
throw cleanup;
} catch (error) {
if (failure === undefined) {
failure = error;
}
}
console.log(failure === primary);Check your prediction
trueThis isolated example begins with an actual primary Error. In a general implementation, a separate failed flag is needed because undefined can itself be the primary thrown reason.
Try the rule on new inputs
Build fixtures for synchronous mapper throw, asynchronous rejection, iterator.next throw and iterator.return throw. State which exact error reaches the caller in each case, including when both primary and cleanup fail.
Trace the contract before building
A library boundary must consider callbacks that throw synchronously, reject asynchronously, ignore cancellation or reenter the owner. Those are different paths through setup, cleanup and settlement. A happy mapper returning a value proves little about them.
Choose one hostile behavior per test and keep the expected outcome precise. A callback that never settles is useful for explaining a limitation, but a routine regression test must remain bounded and report a distinguishing assertion rather than hang. Verify no additional work starts after observed failure, and inspect ownership cleanup as well as the reported error.
Your turn
Cleanup that must not hide the real failure
Write withCleanup(work, cleanup). It calls work() (which may throw before returning a promise, or return one that rejects), then always calls cleanup(). If work failed, reject with its reason, even if cleanup also throws and even if the reason is undefined. If work succeeded but cleanup throws, reject with the cleanup error. Otherwise fulfil with the work's value. The test kit below supplies hostile collaborators and compares rejection reasons by identity. Print:
success, good cleanup: value 1
sync throw undefined, bad cleanup: rejected undefined
rejects primary, bad cleanup: rejected primary
success, bad cleanup: rejected cleanupError
cleanup calls: 4async function main() {
async function withCleanup(work, cleanup) {
// First draft: a throw inside finally replaces the work's failure.
try {
return await work();
} finally {
await cleanup();
}
}
// ---- test kit: hostile collaborators and an outcome recorder ----
let cleanups = 0;
const cleanupError = new Error("cleanup failed");
const primary = new Error("primary");
const goodCleanup = () => {
cleanups += 1;
};
const badCleanup = () => {
cleanups += 1;
throw cleanupError;
};
async function settle(promiseFactory) {
try {
return { ok: true, value: await promiseFactory() };
} catch (reason) {
return { ok: false, reason };
}
}
const name = reason =>
reason === primary ? "primary" : reason === cleanupError ? "cleanupError" : String(reason);
const cases = [
["success, good cleanup", () => withCleanup(async () => 1, goodCleanup)],
["sync throw undefined, bad cleanup", () => withCleanup(() => { throw undefined; }, badCleanup)],
["rejects primary, bad cleanup", () => withCleanup(() => Promise.reject(primary), badCleanup)],
["success, bad cleanup", () => withCleanup(async () => 2, badCleanup)]
];
for (const [label, run] of cases) {
const result = await settle(run);
console.log(`${label}: ${result.ok ? `value ${result.value}` : `rejected ${name(result.reason)}`}`);
}
console.log(`cleanup calls: ${cleanups}`);
}
main();Hint 1: the idea
A throw inside finally wins over whatever the try block was already throwing; that is why the first draft reports cleanupError for two of the cases. To choose which failure wins, you have to catch the work's failure yourself and decide after cleanup has run.
Hint 2: a first step
Run the starter and note which two lines are wrong. Then catch the work's outcome into failed, failure and value variables (a flag, because the reason can be undefined). Call cleanup() in its own try, and only after that decide what to return or throw.
Show one solution
async function main() {
async function withCleanup(work, cleanup) {
let failed = false;
let failure;
let value;
try {
value = await work();
} catch (reason) {
failed = true;
failure = reason;
}
try {
await cleanup();
} catch (cleanupFailure) {
if (!failed) throw cleanupFailure;
}
if (failed) throw failure;
return value;
}
// ---- test kit: hostile collaborators and an outcome recorder ----
let cleanups = 0;
const cleanupError = new Error("cleanup failed");
const primary = new Error("primary");
const goodCleanup = () => {
cleanups += 1;
};
const badCleanup = () => {
cleanups += 1;
throw cleanupError;
};
async function settle(promiseFactory) {
try {
return { ok: true, value: await promiseFactory() };
} catch (reason) {
return { ok: false, reason };
}
}
const name = reason =>
reason === primary ? "primary" : reason === cleanupError ? "cleanupError" : String(reason);
const cases = [
["success, good cleanup", () => withCleanup(async () => 1, goodCleanup)],
["sync throw undefined, bad cleanup", () => withCleanup(() => { throw undefined; }, badCleanup)],
["rejects primary, bad cleanup", () => withCleanup(() => Promise.reject(primary), badCleanup)],
["success, bad cleanup", () => withCleanup(async () => 2, badCleanup)]
];
for (const [label, run] of cases) {
const result = await settle(run);
console.log(`${label}: ${result.ok ? `value ${result.value}` : `rejected ${name(result.reason)}`}`);
}
console.log(`cleanup calls: ${cleanups}`);
}
main();success, good cleanup: value 1
sync throw undefined, bad cleanup: rejected undefined
rejects primary, bad cleanup: rejected primary
success, bad cleanup: rejected cleanupError
cleanup calls: 4The work's outcome is captured first, with a failed flag rather than a truthiness test, so the undefined rejection in case 2 still counts as a failure. cleanup() then runs in every case (4 calls), inside its own try. Its error is rethrown only when there is no primary failure: that is case 4, the only one that reports cleanupError. The first draft's finally let the cleanup error replace undefined and primary in cases 2 and 3. The test kit checks reason === primary by identity, because a different error with the same message would also print "primary" if the test compared text.
Change it and test it
To investigate a missing await safely, first store const failed = Promise.reject("bad") and attach failed.catch(() => {}) to handle its rejection. Pass () => failed to a temporary copy of rejects without await: it incorrectly returns false. The original helper must return true. Handling the fixture separately prevents an unhandled rejection during this experiment. For the pool, identify separate tests for source next failure, mapper failure, external abort and cleanup failure.
Completion is saved in this browser only. It does not measure mastery.