Przejdź do treści głównej
← ⚡ JavaScript & the browser·Moduł C8 · Lekcja 7
ZadanieMake runAll async-aware (await fn()). Write test('resolves to 42', async () => { const v = await Promise.resolve(42); assert(v === 42) }) and test('rejects fails', async () => { await Promise.reject(new Error('boom')) }). Call await runAll(). Expect 1 pass + 1 fail.

Testing async code

125 XP9 min
Teoria

Async tests need an async runner

Update the test runner to await the body. Tests can now be async functions and use await inside.

async function runAll() {
  for (const { name, fn } of tests) {
    try {
      await fn();
      console.log("PASS " + name);
    } catch (err) {
      console.log("FAIL " + name + " — " + err.message);
    }
  }
}

Now you can:

test("fetches user", async () => {
  const user = await loadUser(1);
  assertEqual(user.name, "Anna", "user name");
});

Forgetting await is the #1 async test bug

If you write test("x", () => { somePromise() }) without awaiting somePromise, the runner sees the test "pass" because the function returned without throwing. The Promise's rejection happens AFTER. Always await async work in tests.

🔒

Zarejestruj się, aby zacząć kodować

Teoria jest dostępna dla każdego. Edytor, podgląd na żywo i check odblokowują się z 7-dniowym darmowym okresem próbnym — wymagana karta, anuluj w dowolnym momencie.

Zarejestruj się — darmowy okres próbny →

Pierwsze 10 lekcji w każdej ścieżce jest darmowych. Karta nie jest wymagana.

← PoprzedniaNastępna lekcja →

Codziennie jedna wskazówka Python lub web — na maila

Krótko, ręcznie pisane, bez spamu. Wypisanie w jedno kliknięcie.