| | |

Vitest 08 🧪 Testing Async Code — Promises, async/await, and .resolves/.rejects

⏱️ Estimated read: 10 min | |

Async code is the place where a test passes when it should fail. A test that calls an async function without awaiting it, or awaits a Promise that never settles, or asserts on a Promise instead of its resolved value, will report success while the failure happens in the background. Vitest’s async support is the same as Jest’s in principle—return a Promise or use async/await, and the test runner waits—but the details of the assertion matchers and the timeout behavior are where a test either catches the rejection or misses it.

This chapter covers the three ways to test a Promise, the .resolves and .rejects matchers, and the failure modes that make an async test silently pass. The sections that follow walk through async/await, the promise matchers, and the missing-await problem that is the most common source of false confidence.

Key point: A test must return the Promise or await it; an assertion on a Promise that is not awaited passes before the rejection happens, and .rejects must be used to assert on a rejected Promise rather than relying on a try/catch that swallows the error.


a. async/await and returning the Promise

A test that returns a Promise makes Vitest wait for it. An async test function returns a Promise implicitly, and Vitest waits for it to settle. If the Promise rejects, the test fails; if it resolves, the test passes. The await inside the test is what sequences the assertion after the resolution.

import { describe, it, expect } from "vitest";

async function fetchUser(id: string) {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
}

// async test: Vitest waits for the returned Promise
it("fetches a user", async () => {
  const user = await fetchUser("1");
  expect(user.name).toBe("Ana");
});

// returning the Promise: equivalent
it("fetches a user (returned)", () => {
  return fetchUser("1").then((user) => {
    expect(user.name).toBe("Ana");
  });
});

The two forms are equivalent. The async/await form is the recommended one because it reads like synchronous code and the await makes the sequencing explicit. The returned-Promise form is what the async keyword desugars to, and it is the older pattern.

A test that does not await and does not return the Promise is the failure mode. The test function returns undefined, Vitest considers it complete, and the assertion runs after the test has been reported as passing. The failure is unhandled, and the test suite may report a green run while the console shows an unhandled rejection.

// WRONG: no await, no return
it("fetches a user", () => {
  fetchUser("1").then((user) => {
    expect(user.name).toBe("Ana"); // runs after the test completes
  });
});

b. The .resolves and .rejects matchers

.resolves and .rejects are the matchers for asserting on a Promise without awaiting it manually. .resolves unwraps the resolved value and applies the chained matcher to it; .rejects unwraps the rejection and applies the matcher to the error. Both return a Promise, so the test must await them.

// Resolved value
await expect(fetchUser("1")).resolves.toEqual({ id: "1", name: "Ana" });

// Rejected Promise
await expect(fetchUser("999")).rejects.toThrow("User not found");

// Rejection with a specific error class
await expect(fetchUser("999")).rejects.toThrow(NotFoundError);

// Rejection with an asymmetric matcher
await expect(fetchUser("999")).rejects.toMatchObject({
  message: expect.stringContaining("not found"),
});

The await is not optional. .resolves and .rejects return a Promise, and a test that does not await them completes before the assertion runs. The failure mode is the same as the missing await on a plain Promise: the test reports passing while the assertion fails in the background.

The .rejects matcher is the correct way to assert on a rejection. A try/catch around the call also works, but it is easy to write a catch that asserts nothing and lets every error pass. The .rejects matcher fails if the Promise resolves, which is the assertion that the code was supposed to reject.

// Correct: .rejects fails if the Promise resolves
await expect(fetchUser("999")).rejects.toThrow("not found");

// Risky: a catch that does not assert passes on any error
try {
  await fetchUser("999");
  expect.unreachable("should have thrown"); // the guard that makes it fail
} catch (err) {
  expect((err as Error).message).toContain("not found");
}

The expect.unreachable() guard is what makes the try/catch form safe. Without it, a Promise that resolves instead of rejecting reaches the end of the try block and the test passes with no assertion.


c. The missing-await problem and the timeout

The missing await is the most common async test bug. The test function is declared async but a call inside it is not awaited, or the function is not async at all and the Promise is not returned. Vitest reports the test as passing, and the assertion fails after the test has been torn down.

The lint rules catch some of these. @typescript-eslint/no-floating-promises flags a Promise that is created and not awaited, returned, or caught. vitest/valid-expect and the require-await rules catch the related cases. The rules are not in the default config, and a project that writes async tests should enable them.

The timeout is the second failure mode. A test that awaits a Promise that never settles hangs until the test timeout (5 seconds by default), and then Vitest fails it with a timeout error. The test("...", async () => { ... }, 10_000) third argument sets a custom timeout, and the testTimeout configuration option sets it globally.

// Per-test timeout
it("slow operation", async () => {
  await slowOperation();
}, 10_000);

// Global timeout
// vitest.config.ts
export default defineConfig({
  test: { testTimeout: 10_000 },
});

The --testTimeout CLI flag sets the timeout for a single run. The vi.setConfig({ testTimeout }) call changes it at runtime, and vi.waitFor and vi.waitUntil are the utilities for waiting on a condition with retry rather than a fixed timeout.


Complete Example Session

// ============================================
// PART 1: THE ASYNC FUNCTIONS
// ============================================
async function fetchUser(id: string): Promise<{ id: string; name: string }> {
  if (id === "999") throw new Error("User not found");
  return { id, name: "Ana" };
}

async function slowOperation(): Promise<string> {
  await new Promise((r) => setTimeout(r, 100));
  return "done";
}

// ============================================
// PART 2: async/await
// ============================================
import { describe, it, expect } from "vitest";

describe("fetchUser", () => {
  it("returns the user", async () => {
    const user = await fetchUser("1");
    expect(user.name).toBe("Ana");
  });
});

// ============================================
// PART 3: .resolves / .rejects
// ============================================
describe("promise matchers", () => {
  it("resolves to the user", async () => {
    await expect(fetchUser("1")).resolves.toEqual({ id: "1", name: "Ana" });
  });

  it("rejects for a missing user", async () => {
    await expect(fetchUser("999")).rejects.toThrow("User not found");
  });
});

// ============================================
// PART 4: THE MISSING AWAIT (WRONG)
// ============================================
// it("passes without asserting", () => {
//   fetchUser("1").then((user) => {
//     expect(user.name).toBe("Wrong"); // fails after the test passes
//   });
// });

// ============================================
// PART 5: THE TIMEOUT
// ============================================
it("completes within the timeout", async () => {
  const result = await slowOperation();
  expect(result).toBe("done");
}, 5_000);

The parts covered the async functions, the async/await test, the promise matchers, the missing-await failure, and the timeout.


Quick Reference

Async Test Forms

FormVitest Waits
it("...", async () => { await fn(); })Yes
it("...", () => fn().then(...))Yes (returned)
it("...", () => { fn().then(...); })No (missing return)
it("...", async () => { expect(fn()).resolves... })Only if awaited

Promise Matchers

MatcherAsserts
.resolves.toBe(v)Resolved value
.resolves.toEqual(v)Resolved deep equality
.rejects.toThrow(msg)Rejection message
.rejects.toThrow(ErrorClass)Rejection class
.rejects.toMatchObject(obj)Rejection shape

Timeout

SettingScope
Third argument to itPer-test
testTimeout in configGlobal
--testTimeout CLISingle run
vi.waitForCondition retry

Best Practices

✅ Do This:

// Await the async call
it("...", async () => { const u = await fetchUser("1"); });   // ✅

// Await the promise matcher
await expect(fetchUser("999")).rejects.toThrow("not found");  // ✅

// Guard the try/catch form
try { await fn(); expect.unreachable(); } catch (e) { ... }   // ✅

❌ Don’t Do This:

// Forget the await
it("...", () => { fetchUser("1").then(u => expect(u).toBeDefined()); }); // ❌

// Assert on the Promise itself
expect(fetchUser("1")).toEqual({ id: "1" }); // always fails   // ❌

// Catch without asserting
try { await fn(); } catch {} // passes on any error             // ❌

Common Pitfalls

PitfallWhy It HappensFix
Test passes but assertion failedMissing await/returnAwait or return the Promise
.rejects passes when it should failPromise not awaitedAwait the matcher
Test hangsPromise never settlesSet timeout, check the Promise
try/catch passes on any errorNo assertion in the catchAdd expect.unreachable() guard

Real-World Examples

1. Await the call

it("...", async () => { const u = await fetchUser("1"); });

2. .resolves

await expect(fetchUser("1")).resolves.toEqual({ id: "1", name: "Ana" });

3. .rejects

await expect(fetchUser("999")).rejects.toThrow("not found");

4. Error class

await expect(fn()).rejects.toThrow(NotFoundError);

5. Custom timeout

it("slow", async () => { ... }, 10_000);

6. Global timeout

test: { testTimeout: 10_000 }

7. vi.waitFor

await vi.waitFor(() => expect(element).toBeVisible());

8. Guard the catch

try { await fn(); expect.unreachable(); } catch (e) { ... }

9. Return the Promise

it("...", () => fetchUser("1").then((u) => expect(u).toBeDefined()));

10. Lint rule

@typescript-eslint/no-floating-promises

Visual

The Missing-Await Failure

┌─────────────────────────────────────────────────────────┐
│  it("...", () => {                                      │
│    fetchUser("1").then((u) => {                         │
│      expect(u.name).toBe("Wrong");                      │
│    });                                                  │
│  });                                                    │
│         │                                               │
│         ▼                                               │
│  Test returns undefined → Vitest reports PASS           │
│         │                                               │
│         ▼                                               │
│  Promise resolves → assertion fails in the background   │
│         │                                               │
│         ▼                                               │
│  Unhandled rejection, test already green                │
└─────────────────────────────────────────────────────────┘

.resolves and .rejects

┌─────────────────────────────────────────────────────────┐
│  await expect(Promise).resolves.toBe(value)             │
│         │                                               │
│         ▼                                               │
│  Unwraps the resolved value, applies the matcher        │
│                                                         │
│  await expect(Promise).rejects.toThrow(msg)             │
│         │                                               │
│         ▼                                               │
│  Unwraps the rejection, applies the matcher             │
│  Fails if the Promise resolves                          │
└─────────────────────────────────────────────────────────┘

The try/catch Guard

┌─────────────────────────────────────────────────────────┐
│  try {                                                  │
│    await fn();                                          │
│    expect.unreachable("should have thrown");            │
│  } catch (err) {                                        │
│    expect(err.message).toContain("not found");          │
│  }                                                      │
│                                                         │
│  Without the guard, a resolving Promise passes the test │
└─────────────────────────────────────────────────────────┘

Timeout Flow

┌─────────────────────────────────────────────────────────┐
│  Promise never settles                                  │
│         │                                               │
│         ▼                                               │
│  Vitest waits testTimeout (default 5s)                  │
│         │                                               │
│         ▼                                               │
│  Fails with timeout error                               │
│                                                         │
│  Set a per-test or global timeout for slow operations   │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Async testasync () => { await fn(); }
Returned Promise() => fn().then(...)
Resolved matcher.resolves
Rejected matcher.rejects
Default timeout5s
Per-test timeoutThird argument to it
Missing awaitTest passes, assertion fails silently

Key takeaways:

  • A test must return or await the Promise. An async test function returns a Promise implicitly, and Vitest waits for it. A test that calls an async function without awaiting and without returning completes before the assertion runs, and reports passing .
  • .resolves and .rejects are awaited matchers. They return a Promise, and a test that does not await them completes before the assertion. .rejects fails if the Promise resolves, which is the assertion that the code was supposed to reject .
  • The try/catch form needs a guard. A catch that does not assert passes on any error, and a try that does not throw passes the test. expect.unreachable() after the call is the guard that makes the form safe.
  • The timeout is the failure mode for a hung Promise. The default is 5 seconds, and a Promise that never settles fails the test with a timeout error. The per-test and global timeout settings adjust it .
  • The lint rules catch the missing await. @typescript-eslint/no-floating-promises flags a Promise that is not awaited, returned, or caught, and it is the mechanical guard against the silent-pass failure mode.

Remember: An async test is only as reliable as the await that sequences it. A Promise that is not awaited is a test that has already finished; a .rejects that is not awaited is an assertion that never ran. Await the call, await the matcher, guard the try/catch, and set a timeout for the operations that can hang. The test that passes without asserting is worse than the test that fails, because it hides the failure it was written to catch.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!