Sub topic 4
Testing Promises and async/await
This chapter assumes you can write a basic test with test or it, use expect with matchers such as toBe and toThrow, and read code that uses promises and async/await.
How Vitest knows an async test is finished
Vitest runs your test function and looks at what it returns. If the function returns a promise, Vitest waits for that promise to settle. A rejected promise fails the test. A resolved promise lets the test pass, provided no assertion failed along the way.
An async function always returns a promise. Marking a test async and using await inside it is therefore all Vitest needs to wait correctly.
Awaiting results and rejections
The following file tests one promise that resolves and one that rejects:
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. The second test passes the promise itself to expect. The .rejects modifier unwraps the rejection reason, and toThrow checks the error message. A matching .resolves modifier unwraps a fulfilled value, as in await expect(fetchScore(1)).resolves.toEqual({ id: 1, score: 42 }).
Both modifiers return a promise, so you have to await them (or return them).
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Calling `fetchScore(1).then(...)` without `await` or `return` | The test ends before the callback runs, so the assertion never counts | `await` the promise or `return` it |
| Writing `expect(p).rejects.toThrow()` without `await` | Recent Vitest versions print a warning, but the result is not checked reliably | Always `await expect(...).rejects` |
| Passing a function to `.rejects`, for example `expect(() => p)` | `.rejects` expects a promise, so the assertion errors | Pass the promise itself: `expect(p)` |
| Taking a `done` callback parameter | Vitest does not support `done` callbacks | Use an `async` test or return a promise |
Guarding try/catch tests with expect.assertions
You sometimes need to inspect a rejection in more detail than toThrow allows. A try/catch block handles this, but if the promise resolves by mistake, the catch block never runs and the test passes with no assertions. Call expect.assertions(n) to require exactly n assertions:
import { test, expect } from 'vitest'
function fetchScore(id) {
return id > 0
? Promise.resolve({ id, score: 42 })
: Promise.reject(new Error('Invalid id'))
}
test('rejection carries a useful message', async () => {
expect.assertions(2)
try {
await fetchScore(-5)
} catch (error) {
expect(error).toBeInstanceOf(Error)
expect(error.message).toMatch(/invalid/i)
}
})If fetchScore(-5) resolved, no assertion would run and Vitest would fail the test because it expected two.
Exercise
A teammate writes test('loads', () => { expect(loadConfig()).resolves.toEqual({ debug: false }) }). The test passes even after loadConfig is changed to return { debug: true }. Why, and how do you fix it?
Show answer
The .resolves assertion returns a promise that nothing awaits or returns. The test function returns undefined, so Vitest finishes the test before the comparison runs. Make the test async and write await expect(loadConfig()).resolves.toEqual({ debug: false }), or return the expect expression.
Exercise
Why does a try/catch test for a rejected promise need expect.assertions?
Show answer
If the promise resolves instead of rejecting, the catch block is skipped and the test passes without any assertion. Calling expect.assertions(n) makes Vitest fail the test unless exactly n assertions ran.