Skip to main content
JavaScript & the browser·Module C8 · Lesson 8
TaskWire beforeEach + afterEach into the runner so they run around each test. Track shared state with let counter = 0. beforeEach(() => counter = 0). Inside a test, increment counter twice and assert counter === 2. Run two such tests. Verify each starts from 0.

beforeEach / afterEach

125 XP9 min
Theory

Reset state between tests

beforeEach runs before each test; afterEach runs after. Use them for setup/teardown — the goal is each test starting from a known state.

let beforeFns = [], afterFns = [];
function beforeEach(fn) { beforeFns.push(fn); }
function afterEach(fn)  { afterFns.push(fn); }

async function runAll() {
  for (const { name, fn } of tests) {
    try {
      for (const b of beforeFns) await b();
      await fn();
      console.log("PASS " + name);
    } catch (err) {
      console.log("FAIL " + name + " — " + err.message);
    } finally {
      for (const a of afterFns) {
        try { await a(); } catch (e) { /* afterEach failures shouldn't mask test failures */ }
      }
    }
  }
}

When you need this

  • Restoring monkey-patched globals.
  • Closing connections / files / subscriptions.
  • Resetting a shared cache between tests.
🔒

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial — card required, cancel anytime.

Sign up — free trial →

First 15 lessons in each track are free. No card needed for those.

PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.