The challenge
Write runTests(tests) where each test is { name, fn }. Call each fn. If it throws, the test failed. Return { passed, failed, failures } where failures is an array of the failing tests’ names.
Try it
Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.
It prints
What the tests check
runTests([{ name: "ok", fn: () => {} }, { name: "bad", fn: () => { throw new Error("x"); } }])gives{ passed: 1, failed: 1, failures: ["bad"] }runTests([])gives{ passed: 0, failed: 0, failures: [] }
Hints
Stuck? Open one hint at a time. Try again after each one.
Hint 1
Wrap each fn() in try…catch.
A solution
There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.
Show one possible solution
function runTests(tests) {
const failures = [];
for (const t of tests) {
try {
t.fn();
} catch (error) {
failures.push(t.name);
}
}
return { passed: tests.length - failures.length, failed: failures.length, failures };
}
Learn what you need
This exercise uses what Junior Year: Modules, Node.js & npm: Working Like a Pro teaches. Read those notes first if any of it is new.