Sub topic 3
Making Assertions with expect and Matchers
This chapter assumes you can write a test file with describe and it and run it with npx vitest. You should also know how JavaScript compares primitives and objects.
How an assertion works
An assertion has two parts. expect(value) wraps the value you want to check. A matcher such as toBe or toEqual then compares that value with what you expect. If the comparison fails, the matcher throws an error. Vitest catches the error, marks the test as failed, and prints a diff of the expected and received values.
import { it, expect } from 'vitest'
it('checks a single value', () => {
expect(2 + 2).toBe(4)
expect('vitest').not.toBe('jest')
})You can put .not before any matcher to invert it.
Choosing a matcher
| Matcher | Use it for |
|---|---|
| `toBe(x)` | Primitives, or checking that two references point to the same object (`Object.is`) |
| `toEqual(x)` | Comparing objects and arrays by value, recursively |
| `toStrictEqual(x)` | Same as `toEqual`, but also checks `undefined` properties and class types |
| `toBeNull()`, `toBeUndefined()`, `toBeDefined()` | Checking for specific empty values |
| `toBeTruthy()`, `toBeFalsy()` | Checking truthiness, when the exact value doesn't matter |
| `toBeCloseTo(n, digits)` | Floating-point numbers |
| `toBeGreaterThan(n)`, `toBeLessThanOrEqual(n)` | Numeric ranges |
| `toContain(item)` | An item in an array, or a substring in a string |
| `toMatch(regex)` | Strings that match a pattern |
| `toHaveLength(n)` | The `.length` of arrays and strings |
| `toHaveProperty(path, value?)` | A nested property on an object |
| `toThrow(msg?)` | A function that throws |
Common errors
The test below shows three mistakes people make often. Each assertion is written the correct way, and the comments describe the wrong version.
import { it, expect } from 'vitest'
function parse(json) {
return JSON.parse(json)
}
it('avoids common assertion mistakes', () => {
// 1. toBe on objects fails because they are different references.
// expect({ a: 1 }).toBe({ a: 1 }) -> fails
expect({ a: 1 }).toEqual({ a: 1 })
// 2. Floating-point math is not exact: 0.1 + 0.2 is 0.30000000000000004.
// expect(0.1 + 0.2).toBe(0.3) -> fails
expect(0.1 + 0.2).toBeCloseTo(0.3)
// 3. toThrow needs a function to call. Passing parse('{') directly
// throws before expect runs, so the test crashes.
expect(() => parse('{')).toThrow(SyntaxError)
})Checking part of an object
Often you only care about some of an object's fields. toMatchObject passes if the received object contains the given properties, and any other properties are ignored. Asymmetric matchers such as expect.any(Type) and expect.stringContaining(text) can stand in for values you can't predict.
import { it, expect } from 'vitest'
it('matches the shape of a user', () => {
const user = { id: 17, name: 'Ada', createdAt: new Date(), roles: ['admin'] }
expect(user).toMatchObject({ name: 'Ada', roles: ['admin'] })
expect(user).toEqual({
id: expect.any(Number),
name: 'Ada',
createdAt: expect.any(Date),
roles: expect.arrayContaining(['admin']),
})
expect(user).toHaveProperty('roles.0', 'admin')
})Exercise
The test expect([1, 2, 3]).toBe([1, 2, 3]) fails. Why, and which matcher should you use instead?
Show answer
toBe uses Object.is, which checks whether both sides are the same reference. These are two separate arrays, so the check fails. Use toEqual([1, 2, 3]) to compare the arrays by their contents.
Exercise
You write expect(validate('')).toThrow('Empty input'), and the test crashes with an "Empty input" error instead of passing. What is wrong?
Show answer
validate('') runs and throws before expect gets a value, so the matcher never sees the error. Wrap the call in a function so the matcher can call it and catch the error: expect(() => validate('')).toThrow('Empty input').