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

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.

🔒

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.