Build a mini test runner

“Mini test runner”, a Black belt challenge from the CurlyScript Dojo. It uses what Junior Year: Modules, Node.js & npm: Working Like a Pro teaches, and 2 tests check your answer.

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.

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
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.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning