Sub topic 4
Testing Promises and async/await
Most real JavaScript code is asynchronous at some point: it reads files, calls APIs, or waits on timers. A test for that code has to wait until the work finishes before it checks the result. If the test doesn't wait, it can pass while the code is broken. This chapter shows how Vitest waits for asynchronous work, how to assert on resolved and rejected promises, and which mistakes produce tests that pass when they shouldn't.
This chapter assumes you know how promises and async/await work, and that you have read the earlier chapters on test, describe, and expect matchers such as toBe, toEqual, and toThrow.
How Vitest knows a test is finished
A Vitest test function can return a value. If it returns a promise, Vitest waits for that promise to settle before it marks the test as done:
- If the promise resolves, the test passes, as long as no assertion failed.
- If the promise rejects, the test fails with the rejection reason.
- If the function returns nothing, Vitest treats the test as finished once the function returns.
An async function always returns a promise. Writing async () => { ... } is therefore the simplest way to make Vitest wait. Each await inside the body pauses the test until that step settles. An assertion that throws inside an async function rejects the returned promise, and Vitest reports that rejection as a failed test.
The two core patterns
The following file tests a function that returns a promise. It covers the success path and the failure path:
import { test, expect } from 'vitest'
function fetchScore(id) {
return id > 0
? Promise.resolve({ id, score: 42 })
: Promise.reject(new Error('Invalid id'))
}
test('resolves with the score', async () => {
const result = await fetchScore(1)
expect(result.score).toBe(42)
})
test('rejects for an invalid id', async () => {
await expect(fetchScore(0)).rejects.toThrow('Invalid id')
})The first test awaits the value and then makes ordinary synchronous assertions on it. Use this pattern when you want several checks on one result.
The second test uses .rejects. expect(promise).rejects waits for the promise and then applies the next matcher to the rejection reason. If the promise resolves instead, the assertion fails. The await in front of it is required, as the next sections explain.
resolves and rejects
.resolves is the counterpart of .rejects. It unwraps the resolved value and passes it to the matcher:
import { test, expect } from 'vitest'
function loadConfig() {
return Promise.resolve({ retries: 3, verbose: false })
}
function failWithCode() {
return Promise.reject({ code: 'E_TIMEOUT' })
}
test('resolves to the default config', async () => {
await expect(loadConfig()).resolves.toEqual({ retries: 3, verbose: false })
})
test('rejects with a plain object, not an Error', async () => {
await expect(failWithCode()).rejects.toEqual({ code: 'E_TIMEOUT' })
})Pick the matcher based on what the promise rejects with:
| Rejection reason | Matcher to use | Example |
|---|---|---|
| An `Error` instance | `rejects.toThrow` | `rejects.toThrow('Invalid id')` |
| An `Error` of a specific class | `rejects.toThrow` with the class | `rejects.toThrow(TypeError)` |
| A plain object | `rejects.toEqual` or `rejects.toMatchObject` | `rejects.toMatchObject({ code: 'E_TIMEOUT' })` |
| A string or number | `rejects.toBe` | `rejects.toBe('not found')` |
toThrow checks the message of an Error. With a string argument it passes when the message contains that string. With a regular expression it passes when the message matches the pattern.
Common errors
Forgetting to await
This is the most common async testing mistake:
import { test, expect } from 'vitest'
function fetchScore(id) {
return new Promise((resolve) => {
setTimeout(() => resolve({ id, score: 0 }), 10)
})
}
test('BROKEN: no await, no return', () => {
fetchScore(1).then((result) => {
expect(result.score).toBe(42) // runs after the test is already over
})
})The test function returns undefined, so Vitest records a pass right away. The callback in .then runs 10 milliseconds later. At that point its failed assertion belongs to no test. At best, Vitest reports it as an unhandled error. At worst, the run has already finished and nobody sees it.
The same problem affects .resolves and .rejects. They return a promise, so expect(p).rejects.toThrow() without await checks nothing before the test ends. Recent Vitest versions print a warning when one of these assertions is not awaited. Don't rely on the warning. Write the await every time.
Any of these fixes works:
- Make the test
asyncandawaitthe call. - Return the promise:
return fetchScore(1).then(...). - Use
await expect(...).resolves.
Option 1 reads most clearly and is the usual choice.
The try/catch trap
A tempting way to test a rejection is this:
import { test, expect } from 'vitest'
async function parseAge(input) {
const age = Number(input)
if (Number.isNaN(age)) {
throw new Error('Not a number')
}
return age
}
test('BROKEN: passes even if nothing throws', async () => {
try {
await parseAge('42') // does not throw
} catch (error) {
expect(error.message).toBe('Not a number')
}
})If parseAge stops throwing, the catch block never runs, no assertion runs, and the test passes. Use await expect(parseAge('abc')).rejects.toThrow('Not a number') instead. It fails when the promise resolves.
Sometimes you need try/catch, for example to inspect several properties of a custom error. In that case, tell Vitest how many assertions must run:
import { test, expect } from 'vitest'
class HttpError extends Error {
constructor(status, message) {
super(message)
this.status = status
}
}
async function request(path) {
throw new HttpError(404, `No route for ${path}`)
}
test('reports status and path', async () => {
expect.assertions(2)
try {
await request('/missing')
} catch (error) {
expect(error.status).toBe(404)
expect(error.message).toContain('/missing')
}
})expect.assertions(2) makes the test fail unless exactly two assertions ran. expect.hasAssertions() is a looser version that requires at least one. Both protect against code paths that silently skip the assertions.
Using a done callback
Older Jest tests sometimes take a done parameter and call it when the work finishes. Vitest does not support this style. Its first parameter is a test context object, not done. Wrap callback-based APIs in a promise instead:
import { test, expect } from 'vitest'
function readValue(callback) {
setTimeout(() => callback(null, 'ready'), 5)
}
test('wraps a callback API in a promise', async () => {
const value = await new Promise((resolve, reject) => {
readValue((error, result) => (error ? reject(error) : resolve(result)))
})
expect(value).toBe('ready')
})For Node.js callback APIs that follow the (error, result) convention, util.promisify from node:util does the same job.
Timeouts
A promise that never settles would hang the test forever, so Vitest fails any test that runs longer than 5,000 milliseconds by default. You can change the limit for one test with a third argument, or for every test with the testTimeout option in the configuration (covered in a later chapter):
import { test, expect } from 'vitest'
function slowOperation() {
return new Promise((resolve) => setTimeout(() => resolve('done'), 6000))
}
test('allows a slow operation', async () => {
await expect(slowOperation()).resolves.toBe('done')
}, 10000)A timeout failure usually means one of three things. A promise is never resolved, for example because a mock never returns. A real network call is slower than expected. Or the test waits on a real timer. Raising the limit is rarely the right fix for a unit test. Mock the slow dependency or use fake timers, which later chapters cover.
Waiting for a condition with vi.waitFor
Sometimes the code under test starts async work but does not return its promise, such as a fire-and-forget save. vi.waitFor calls a callback over and over until it stops throwing or a timeout expires:
import { test, expect, vi } from 'vitest'
const store = { saved: false }
function saveInBackground() {
setTimeout(() => {
store.saved = true
}, 50)
}
test('eventually saves', async () => {
saveInBackground()
await vi.waitFor(() => {
expect(store.saved).toBe(true)
}, { timeout: 1000, interval: 20 })
})Use it sparingly. If you control the code, returning the promise makes the test simpler and faster.
Quick reference
| Goal | Pattern |
|---|---|
| Check a resolved value in detail | `const v = await fn(); expect(v)...` |
| One-line check of a resolved value | `await expect(fn()).resolves.toEqual(...)` |
| Check a rejected `Error` | `await expect(fn()).rejects.toThrow('msg')` |
| Check a rejected non-Error value | `await expect(fn()).rejects.toEqual(...)` |
| Guarantee assertions ran | `expect.assertions(n)` or `expect.hasAssertions()` |
| Test a callback API | Wrap it in `new Promise(...)` and await it |
| Allow a longer run | Third argument to `test`, or `testTimeout` |
Exercise
This test passes, yet getTotal is known to reject with new Error('Cart is empty') for an empty cart. Explain why it passes and rewrite it so it actually checks the rejection: test('empty cart', () => { expect(getTotal([])).rejects.toThrow('Cart is empty') })
Show answer
The .rejects assertion returns a promise that nobody awaits or returns. The test function returns undefined, so Vitest marks it as passed before the assertion runs. Fix it by making the test async and awaiting the assertion: test('empty cart', async () => { await expect(getTotal([])).rejects.toThrow('Cart is empty') }). Returning the expression (return expect(...).rejects.toThrow(...)) also works.
Exercise
A function loadUser(id) rejects with the plain object { status: 401, reason: 'expired' }. Why is rejects.toThrow() a poor fit, and which assertion would you write instead?
Show answer
toThrow is meant for Error instances and matches on their message. A plain object has no error message to match, so the assertion fails or checks nothing useful. Assert on the object's shape instead: await expect(loadUser(1)).rejects.toEqual({ status: 401, reason: 'expired' }), or use rejects.toMatchObject({ status: 401 }) to check only the status.
Exercise
A test uses try/catch to inspect an error thrown by an awaited call and has two expect calls in its catch block. What single line protects it against the case where the call stops throwing, and where does it go?
Show answer
Put expect.assertions(2) at the start of the test body, before the try block. If the call resolves, the catch block never runs, zero assertions execute, and the test fails instead of passing silently.