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