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: [] });
}
});
}
new Promise((resolve, reject) => { ... })makes a Promise. Inside its function, you decide the outcome of that Promise.resolve(value)means success: the Promise settles carryingvalue.reject(new Error("..."))means failure: the Promise is rejected, carrying that error.url.includes("users")istruewhen the texturlcontains the wordusers.
| 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"])
})
})
async () => { ... }: the test callback (the function given toit) is markedasync, so it may useawaitinside. Withoutasync,awaitin that callback is a syntax error (a mistake in how the code is written), and the test file doesn't run at all.await getData("/users")waits for the Promise to settle, then takes what it carries:{ data: ["Budi", "Siti"] }.- An
asyncfunction always returns a Promise. Vitest receives that Promise and waits for it to finish before it decides whether the test passed or failed.
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")
})
.resolveswaits for the Promise to settle, then runs its matcher (toEqual,toBe) on what it carries..rejectsexpects the Promise to be rejected instead.toThrow("Failed to fetch data")checks that the error message contains that text.- You still have to write the
awaitin front ofexpect. Since Vitest 5, a test that forgets thisawaitfails withPromise returned by ... was not awaited, even when the assertion is correct. Vitest 4 still waited by itself and only printed a warning. - If the Promise succeeds (resolves) instead, as
getData("/empty")does,.rejectsfails withAssertionError: promise resolved "{ data: [] }" instead of rejecting.
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))
awaiton a rejected Promise throws its error, so wrap it intry/catch. Withouttry/catch, the function stops on that line.e.messageholds the error's text,"Failed to fetch data".testFetchDataisasyncitself, so its result is a Promise too. The number is printed through.then((count) => console.log(count)). When all three cases are right, it prints3.
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" |
vi.useFakeTimers()replacessetTimeout,setIntervalandDatewith versions whose clock you control.vi.advanceTimersByTime(1000)moves the clock 1,000 ms ahead and runs every timer whose time has come. The test still finishes in a few milliseconds.vi.fn()is the fake function from the lesson Mocking & Stubbing: it records every call it gets.vi.useRealTimers()inafterEachbrings the real timers back, so other tests don't run on the fake clock.
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
- Forgetting
asyncon the test callback.awaitin a plain function is a syntax error, so the whole test file fails to load. - Forgetting
awaitin front ofexpect(...).resolvesor.rejects. In Vitest 5 the test fails, even when the assertion is correct (Vitest 4 only warned). Always writeawait expect(...). expectinside.thenwith noawaitorreturn. The test shows ✓ even when the result is wrong. A test that can't fail protects nothing.- Forgetting
vi.useRealTimers(). The next tests still run on the fake clock, so theirsetTimeoutnever runs. Put it inafterEach. - Checking a value you typed yourself.
expect({ status: "ok" }).toEqual({ status: "ok" })always passes. Check the result of the call:expect(result)orexpect(await getData("/users")).
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.