Testing Async Code

A Promise carries a result that arrives later: resolve on success, reject (rejected) on failure. In a test, mark the callback (the function inside it) async…

Look at this test. getData is a function that pretends to fetch data from a server (its code is below), and getData("/empty") always gives empty data. Yet this test checks that the data holds two names. The check is inside .then, without await. Before you read on, guess: does Vitest mark it ✓ (passed) or × (failed)?

it("data /empty holds two names", () => {
  getData("/empty").then((result) => {
    expect(result.data).toHaveLength(2)
  })
})

The answer is in the part "Forgetting to wait: a false pass" below. The reason is async code: code whose result arrives later, like a request to a server, a setTimeout timer, or reading a file. In JavaScript, a result that hasn't arrived yet is wrapped in a Promise. Picture ordering food at a food court. The cashier gives you a buzzer (a device that beeps when the food is ready), and the food comes later. If you photograph your tray the moment the buzzer is in your hand, the tray is still empty. In code, the buzzer is the Promise, the food is the result you wait for, and photographing the tray is expect. So an async test has to wait for the buzzer to beep (the Promise to settle, which means to finish, with success or failure) before it checks what's inside.

Promise: a promise that settles later

This is the function used throughout this lesson. getData pretends to fetch data from a server, with no real server:

function getData(url) {
  return new Promise((resolve, reject) => {
    if (url.includes("users")) {
      resolve({ data: ["Budi", "Siti"] });
    } else if (url.includes("error")) {
      reject(new Error("Failed to fetch data"));
    } else {
      resolve({ data: [] });
    }
  });
}
Call What its Promise does
getData("/users") resolves { data: ["Budi", "Siti"] }
getData("/error") rejects Error("Failed to fetch data")
getData("/empty") resolves { data: [] }

async and await inside a test

The test below waits for the result of getData("/users") before it checks it:

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

describe("getData", () => {
  it("gives two names for /users", async () => {
    const result = await getData("/users")
    expect(result.data).toEqual(["Budi", "Siti"])
  })
})

If you forget to write await, result holds the Promise itself (the buzzer), not the data. So result.data is undefined, and Vitest writes:

AssertionError: expected undefined to deeply equal [ 'Budi', 'Siti' ]

resolves and rejects: check a Promise directly

Another way: give the Promise straight to expect, then add .resolves or .rejects before the matcher:

it("gives two names for /users", async () => {
  await expect(getData("/users")).resolves.toEqual({ data: ["Budi", "Siti"] })
})

it("is rejected for /error", async () => {
  await expect(getData("/error")).rejects.toThrow("Failed to fetch data")
})

Catching a rejected Promise with try/catch

You can also test a Promise without Vitest. In the exercise, you use this pattern: you count the passing cases yourself.

async function testFetchData() {
  let passed = 0

  try {
    await getData("/error")
  } catch (e) {
    if (e.message === "Failed to fetch data") passed++
  }

  // two more cases: "/users" (data.length 2) and another url (data.length 0)
  return passed
}

testFetchData().then((count) => console.log(count))

Forgetting to wait: a false pass

Back to the test at the start of the lesson. It comes out ✓, passed, even though the data is empty. Vitest 5 writes:

 ✓ src/getData.test.js > getData > data /empty holds two names 2ms

The callback isn't async and returns nothing. So for Vitest, the test is over as soon as that callback finishes running. The body of .then only runs after that, and the failing expect inside it is no longer part of the test. In this example getData settles at once. So Vitest happens to still catch the error from that expect, and reports it in a separate block, Unhandled Rejection, with the message This might cause false positive tests (tests may pass falsely). But when the data comes from a real server that needs 300 ms, all the tests are already over, and nothing reports it.

The fix: mark the callback async, then await the Promise (or return the Promise, so Vitest waits for it).

Fake timers: move the clock without waiting

Code with setTimeout (which runs a function after a delay) doesn't need real waiting. Vitest can replace the clock that timers use with a fake clock (fake timers), and you move that fake clock forward yourself. In the code below, delayedHello calls callback("hello") after 1,000 ms:

import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"

function delayedHello(callback) {
  setTimeout(() => {
    callback("hello")
  }, 1000)
}

describe("delayedHello", () => {
  beforeEach(() => {
    vi.useFakeTimers()
  })

  afterEach(() => {
    vi.useRealTimers()
  })

  it("calls the callback after 1 second", () => {
    const callback = vi.fn()
    delayedHello(callback)
    expect(callback).not.toHaveBeenCalled()

    vi.advanceTimersByTime(1000)
    expect(callback).toHaveBeenCalledWith("hello")
  })
})

This table moves the fake clock in two steps, 999 ms and then 1 ms, to show when callback is called:

Step Fake clock callback called?
delayedHello(callback) 0 ms not yet, its timer is scheduled at 1,000 ms
vi.advanceTimersByTime(999) 999 ms not yet
vi.advanceTimersByTime(1) 1,000 ms yes, with "hello"

Without vi.useFakeTimers(), calling vi.advanceTimersByTime throws an error right away:

Error: A function to advance timers was called but the timers APIs are not mocked. Call `vi.useFakeTimers()` in the test file first.

⚠️ What is often forgotten in async tests

TL;DR: A Promise carries a result that arrives later: resolve on success, reject (rejected) on failure. In a test, mark the callback (the function inside it) async, then await the Promise before checking. await expect(p).resolves.toEqual(...) checks what a successful Promise carries, and await expect(p).rejects.toThrow("...") checks a rejected one. Without Vitest, catch a rejection with try/catch. An expect inside .then without await makes a test pass falsely: it passes even when the result is wrong. For setTimeout, use vi.useFakeTimers() (a fake clock), move the clock with vi.advanceTimersByTime(ms), and bring the real timers back with vi.useRealTimers() in afterEach.

⚡ async and await in a test

Write:

it("gives two names for /users", async () => {
  const result = await getData("/users")
  expect(result.data).toEqual(["Budi", "Siti"])
})

Meaning: getData("/users") returns a Promise (a promise that the result arrives later) that carries two names. The callback (the function inside it) is marked async so it may use await. await waits for the Promise to settle (to finish), then takes what it carries. Without await, result is still a Promise, and result.data is undefined.

⚡ resolves and rejects

Write:

await expect(getData("/error")).rejects.toThrow("Failed to fetch data")

Meaning: getData("/error") returns a Promise that is rejected with the error Failed to fetch data. .rejects checks a rejected Promise, and .resolves checks what a successful Promise carries. Keep the await in front of expect, so the test waits for that check to finish.

⚡ Forgetting to wait: a false pass

Guess first: getData("/empty") gives empty data, but the test checks expect(result.data).toHaveLength(2) inside .then, with no await. Does it show ✓ (passed) or × (failed)?

✓, passed, even though the data is empty. For Vitest, the test is over before the body of .then runs.

Meaning: The fix: mark the test callback async, then await the Promise (or return it).

⚡ Fake timers: move the clock without waiting

Write:

vi.useFakeTimers()
vi.advanceTimersByTime(1000)
vi.useRealTimers()

Meaning: vi.useFakeTimers() replaces the clock for timers such as setTimeout with a fake clock. vi.advanceTimersByTime(1000) moves that fake clock 1,000 ms ahead without waiting, and runs the timers whose time has come. vi.useRealTimers() in afterEach brings the real timers back, so other tests don't run on the fake clock.

What you will learn