MediumJavaScriptTypeScript

Implement Test Runner (describe/it)

TestingJavaScriptFunctions

Implement solve(plan) where plan is a serialised test suite:

{
  suites: [
    {
      name: 'Math',
      beforeEach: 'counter++',   // JS expression appended to a harness
      afterEach: null,
      tests: [
        { name: 'adds', body: 'return counter === 1' },
        { name: 'still increments', body: 'return counter === 2' },
      ],
    }
  ]
}

Each beforeEach / afterEach / test body is a JS statement string
executed with new Function against a shared mutable context object
{ counter: 0 } that is reset to {} before each suite.

A test passes if its body returns true. Any other return value or a
thrown error means failure.

Return:

{
  passed: number,   // count of passing tests
  failed: number,   // count of failing tests
  results: [
    { suite: string, test: string, pass: boolean, error: string | null }
  ]
}

Rules:

  • beforeEach runs before every test in the suite (including after failures).
  • afterEach runs after every test, even if the test threw.
  • If beforeEach throws, the test is marked failed with the error message; afterEach still runs.
  • null means the hook is absent.

Sample tests

Test #1beforeEach increments shared counter — both tests pass
Input: [{"suites":[{"name":"Math","tests":[{"body":"return counter === 1","name":"first"},{"body":"return counter === 2","name":"second"}],"afterEach":null,"beforeEach":"counter = (counter || 0) + 1"}]}]
Output: {"failed":0,"passed":2,"results":[{"pass":true,"test":"first","error":null,"suite":"Math"},{"pass":true,"test":"second","error":null,"suite":"Math"}]}
Test #2test returning false counts as failed
Input: [{"suites":[{"name":"Fail","tests":[{"body":"return 1 === 2","name":"wrong"}],"afterEach":null,"beforeEach":null}]}]
Output: {"failed":1,"passed":0,"results":[{"pass":false,"test":"wrong","error":"Test returned false","suite":"Fail"}]}
Test #3test that throws records error message
Input: [{"suites":[{"name":"Throws","tests":[{"body":"throw new Error(\"bad\")","name":"error"}],"afterEach":null,"beforeEach":null}]}]
Output: {"failed":1,"passed":0,"results":[{"pass":false,"test":"error","error":"bad","suite":"Throws"}]}