Sub topic 1
Installing Vitest and Running Your First Test
Prerequisites
This chapter assumes you already know:
- Modern JavaScript: ES modules, arrow functions, and destructuring
- Promises and async/await
- npm or another Node.js package manager
- How to run commands in a terminal
Installing Vitest
Add Vitest as a dev dependency:
npm install -D vitestVitest has two run modes:
| Command | Behavior |
|---|---|
| `npx vitest` | Watch mode. It reruns the affected tests whenever you save a file. |
| `npx vitest run` | Runs every test once and exits. Use this in CI. |
Vitest finds files whose names match *.test.js or *.spec.js.
Organizing Tests with describe, test, and it
test() defines one test, and it() is an alias for it. describe() groups related tests so the output reads as a hierarchy.
// math.js
export function add(a, b) {
return a + b
}
export function divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero')
}
return a / b
}
// math.test.js
import { describe, it, expect } from 'vitest'
import { add, divide } from './math.js'
describe('math', () => {
it('adds two numbers', () => {
expect(add(2, 3)).toBe(5)
})
it('throws when dividing by zero', () => {
expect(() => divide(1, 0)).toThrow('Cannot divide by zero')
})
it('compares objects by value with toEqual', () => {
expect({ total: add(1, 1) }).toEqual({ total: 2 })
})
})Making Assertions with expect and Matchers
expect(value) wraps a value, and a matcher checks it. The following mistakes are the most common:
toBeusesObject.is, so two objects with the same contents are still not equal under it. UsetoEqualto compare structure.toThrowneeds a function to call. If you writeexpect(divide(1, 0)), the error is thrown beforeexpectruns, and the test crashes instead of passing.
Testing Promises and async/await
Make the test function async and await the result. For promises that should reject, await expect(...).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')
})Exercise
Why does expect({ a: 1 }).toBe({ a: 1 }) fail, and which matcher makes the assertion pass?
Show answer
toBe compares with Object.is, so it checks identity, and the two object literals are different objects. Use toEqual, which compares the objects by value.
Exercise
Write an assertion that fetchScore(-5) rejects with "Invalid id".
Show answer
await expect(fetchScore(-5)).rejects.toThrow('Invalid id'), placed inside an async test function.