AufgabeWire 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
Theorie
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.
🔒
Anmelden, um zu programmieren
Theorie ist für alle offen. Editor, Live-Preview und Check werden mit 7-Tage-Gratis-Test freigeschaltet — Karte erforderlich, jederzeit kündbar.
Registrieren — Gratis-Test →Die ersten 10 Lektionen jedes Tracks sind kostenlos. Keine Karte nötig.