Aller au contenu principal
← ⚡ JavaScript & the browser·Module C8 · Leçon 8
TâcheWire 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
Théorie

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

Inscris-toi pour coder

La théorie est ouverte à tous. L'éditeur, l'aperçu live et le check se débloquent avec un essai gratuit de 7 jours — carte requise, annulable à tout moment.

S'inscrire — essai gratuit →

Les 10 premières leçons de chaque parcours sont gratuites. Pas de carte requise.

← PrécédentLeçon suivante →

Recevez une astuce Python ou web par jour — par email

Court, écrit à la main, sans spam. Désabonnement en un clic.