Μετάβαση στο κύριο περιεχόμενο
← ⚡ JavaScript & the browser·Ενότητα C8 · Μάθημα 8
ΕργασίαWire 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
Θεωρία

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

Εγγράψου για να αρχίσεις να προγραμματίζεις

Η θεωρία είναι ανοιχτή για όλους. Ο επεξεργαστής, η ζωντανή προεπισκόπηση και ο έλεγχος ξεκλειδώνουν με 7-ήμερη δωρεάν δοκιμή — απαιτείται κάρτα.

Εγγραφή — δωρεάν δοκιμή →

Τα πρώτα 10 μαθήματα κάθε διαδρομής είναι δωρεάν. Δεν χρειάζεται κάρτα.

← ΠροηγούμενοΕπόμενο μάθημα →

Μια συμβουλή Python ή web την ημέρα — με email

Σύντομο, γραμμένο στο χέρι, χωρίς spam. Διαγραφή με ένα κλικ.