Перейти до основного вмісту
← ⚡ 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-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.