Sub topic 3
Making Assertions with expect and Matchers
This chapter assumes you can write and run a Vitest test file with describe and it, as covered in the previous two chapters. It also assumes you are comfortable with ES modules, arrow functions, and JavaScript's equality rules (=== compared with deep comparison).
An assertion checks that a value is what you expect. If it is not, the assertion throws an error and Vitest marks the test as failed. In Vitest, every assertion has two parts:
expect(received)wraps the value your code produced.- A matcher, such as
.toBe(expected), compares that value against your expectation.
Picking the right matcher matters for two reasons. A matcher that is too loose lets bugs through. A matcher that is too strict breaks whenever a harmless detail changes.
How expect Works
expect returns an assertion object, and matchers are methods on that object. When a matcher fails, it throws an AssertionError that holds the received value, the expected value, and a diff. Vitest catches the error, stops that test, and prints the diff.
The first failing assertion stops the test, so any assertions after it never run. Keep this in mind when you put several assertions in one test (the expect.soft section below shows a way around it).
Identity Versus Equality: toBe, toEqual, toStrictEqual
Developers choose between these three matchers more often than any others, and they mix them up more often too.
| Matcher | Compares with | Use for |
|---|---|---|
| `toBe` | `Object.is` | Primitives, or checking that two references point to the same object |
| `toEqual` | Recursive deep equality, ignoring `undefined` properties | Plain data where the shape and values matter |
| `toStrictEqual` | Deep equality plus `undefined` keys, sparse arrays, and class types | Data where those details are part of the contract |
// equality.test.js
import { describe, it, expect } from 'vitest'
class Point {
constructor(x, y) {
this.x = x
this.y = y
}
}
describe('equality matchers', () => {
it('toBe uses Object.is', () => {
expect(2 + 2).toBe(4)
expect(NaN).toBe(NaN) // passes: Object.is(NaN, NaN) is true
expect(0).not.toBe(-0) // Object.is(0, -0) is false
})
it('toBe fails for two objects with the same contents', () => {
const a = { id: 1 }
expect(a).toBe(a) // same reference
expect({ id: 1 }).not.toBe({ id: 1 })
expect({ id: 1 }).toEqual({ id: 1 })
})
it('toEqual ignores undefined properties and class types', () => {
expect({ id: 1, note: undefined }).toEqual({ id: 1 })
expect(new Point(1, 2)).toEqual({ x: 1, y: 2 })
})
it('toStrictEqual does not', () => {
expect({ id: 1, note: undefined }).not.toStrictEqual({ id: 1 })
expect(new Point(1, 2)).not.toStrictEqual({ x: 1, y: 2 })
expect(new Point(1, 2)).toStrictEqual(new Point(1, 2))
})
})A good default is toEqual for plain data returned by your functions. Use toStrictEqual when the code under test must return a specific class instance, or when the difference between a missing key and a key set to undefined matters. For example, the difference matters for an object that gets serialized and sent to an API that treats the two cases differently.
Truthiness and Nullish Values
| Matcher | Passes when the value is |
|---|---|
| `toBeTruthy()` | truthy (`if (value)` would run) |
| `toBeFalsy()` | one of `false`, `0`, `''`, `null`, `undefined`, `NaN` |
| `toBeNull()` | exactly `null` |
| `toBeUndefined()` | exactly `undefined` |
| `toBeDefined()` | anything except `undefined` |
Prefer the precise matchers. expect(findUser(9)).toBeFalsy() passes whether the function returns null, undefined, 0, or an empty string. If your contract says it returns null, write toBeNull(). That way a change to undefined gets caught.
Numbers
// numbers.test.js
import { it, expect } from 'vitest'
it('compares numbers', () => {
expect(10).toBeGreaterThan(9)
expect(10).toBeGreaterThanOrEqual(10)
expect(3).toBeLessThan(4)
expect(3).toBeLessThanOrEqual(3)
})
it('handles floating point with toBeCloseTo', () => {
expect(0.1 + 0.2).not.toBe(0.3) // 0.30000000000000004
expect(0.1 + 0.2).toBeCloseTo(0.3) // default: 2 decimal digits
expect(Math.PI).toBeCloseTo(3.14159, 5)
})toBeCloseTo(expected, numDigits) passes when the difference is less than 10 ** -numDigits / 2. numDigits defaults to 2, which is loose. For money or scientific values, pass a larger numDigits. You can also avoid floats entirely, for example by storing money as whole cents.
Strings, Arrays, and Objects
// collections.test.js
import { it, expect } from 'vitest'
const order = {
id: 'A-17',
status: 'paid',
items: [{ sku: 'pen', qty: 2 }, { sku: 'ink', qty: 1 }],
customer: { name: 'Ada', address: { city: 'London' } },
}
it('checks strings', () => {
expect(order.id).toMatch(/^A-\d+$/)
expect('Payment failed: card declined').toMatch('card declined')
expect(order.status).toContain('ai') // substring
})
it('checks arrays', () => {
const skus = order.items.map((i) => i.sku)
expect(skus).toContain('pen') // uses ===
expect(order.items).toContainEqual({ sku: 'ink', qty: 1 }) // deep
expect(order.items).toHaveLength(2)
})
it('checks object properties', () => {
expect(order).toHaveProperty('status', 'paid')
expect(order).toHaveProperty('customer.address.city', 'London')
expect(order).toHaveProperty(['items', 0, 'sku'], 'pen')
})
it('checks part of an object with toMatchObject', () => {
expect(order).toMatchObject({
status: 'paid',
customer: { name: 'Ada' },
})
})toContain uses ===, so it cannot find an object inside an array unless you hold the same reference. Use toContainEqual for that.
toMatchObject passes when the received object contains the expected properties, and it ignores any extra ones. This helps when a function returns a large object and the test cares about only a few fields. Asserting on the fields that matter keeps tests from breaking when unrelated fields are added.
Errors: toThrow
toThrow must receive a function that Vitest can call. If you call the throwing code yourself, the error is thrown before expect runs, and the test fails with that raw error.
// errors.test.js
import { it, expect } from 'vitest'
class ValidationError extends Error {}
function parseAge(input) {
const n = Number(input)
if (!Number.isInteger(n) || n < 0) {
throw new ValidationError(`Invalid age: ${input}`)
}
return n
}
it('throws on bad input', () => {
expect(() => parseAge('abc')).toThrow() // any error
expect(() => parseAge('abc')).toThrow('Invalid age') // message substring
expect(() => parseAge('-1')).toThrow(/^Invalid age: -1$/)// message regex
expect(() => parseAge('abc')).toThrow(ValidationError) // error class
expect(() => parseAge('42')).not.toThrow()
})A bare toThrow() passes for any error, including a TypeError caused by a typo in your own code. Always pass a message, regex, or class so the test proves the code threw the error you intended. Rejected promises use .rejects.toThrow and are covered in the next chapter.
Negation with .not
You can put .not in front of any matcher to invert it. Use it sparingly. expect(result).not.toBe(5) passes for every value except 5, including undefined. A negative assertion is weak on its own, so pair it with a positive one when you can.
Asymmetric Matchers
Sometimes part of a value cannot be predicted, such as a generated ID or a timestamp. Asymmetric matchers are placeholders you put inside the expected value. Each one matches a category of values:
// asymmetric.test.js
import { it, expect } from 'vitest'
function createUser(name) {
return {
id: Math.random().toString(36).slice(2),
name,
createdAt: new Date(),
tags: ['new', 'unverified'],
}
}
it('matches values that cannot be predicted exactly', () => {
expect(createUser('Ada')).toEqual({
id: expect.any(String),
name: 'Ada',
createdAt: expect.any(Date),
tags: expect.arrayContaining(['new']),
})
})
it('combines with other matchers', () => {
expect(createUser('Grace')).toEqual(
expect.objectContaining({ name: expect.stringContaining('Gra') }),
)
expect(createUser('Lin').id).toEqual(expect.stringMatching(/^[a-z0-9]+$/))
})| Asymmetric matcher | Matches |
|---|---|
| `expect.any(Constructor)` | Any value created by that constructor, or a primitive of that type |
| `expect.anything()` | Anything except `null` and `undefined` |
| `expect.objectContaining(obj)` | An object that has at least these properties |
| `expect.arrayContaining(arr)` | An array that contains these elements in any order |
| `expect.stringContaining(str)` | A string that contains the substring |
| `expect.stringMatching(regex)` | A string that matches the pattern |
These matchers become especially useful with mock call assertions such as toHaveBeenCalledWith, covered in a later chapter.
Soft Assertions
expect.soft records a failure without stopping the test. The test still fails, but every soft assertion runs and reports its own failure, so you see every wrong field in one run:
// soft.test.js
import { it, expect } from 'vitest'
it('reports every mismatched field', () => {
const config = { port: 8080, host: 'localhost', debug: false }
expect.soft(config.port).toBe(8080)
expect.soft(config.host).toBe('localhost')
expect.soft(config.debug).toBe(false)
})Use expect.soft when several independent checks belong to one test. Do not use it when a later assertion only makes sense if an earlier one passed.
Choosing a Matcher
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `toBe` fails on identical-looking objects | Reference comparison | Use `toEqual` |
| `0.1 + 0.2` is not `0.3` | Floating-point rounding | Use `toBeCloseTo` |
| Test fails with the raw error instead of passing `toThrow` | Called the function directly | Wrap it: `expect(() => fn())` |
| `toEqual` passes but the API rejects the payload | `undefined` keys ignored | Use `toStrictEqual` |
| `toContain` misses an object in an array | `===` comparison | Use `toContainEqual` |
Exercise
The function buildPayload() returns { name: 'Ada', email: undefined }. The test expect(buildPayload()).toEqual({ name: 'Ada' }) passes, but the server rejects payloads that contain an email key. Which matcher would catch this, and why does toEqual miss it?
Show answer
Use expect(buildPayload()).toStrictEqual({ name: 'Ada' }). toEqual treats a property set to undefined as equivalent to a missing property, so it ignores the email key. toStrictEqual checks undefined properties, so it fails and reports the extra key.
Exercise
This assertion fails with "Error: Invalid age: x" instead of passing: expect(parseAge('x')).toThrow(ValidationError). Explain why and fix it.
Show answer
parseAge('x') runs and throws before expect is called, so the matcher never sees the error. Pass a function so Vitest can call it and catch the error: expect(() => parseAge('x')).toThrow(ValidationError).
Exercise
Write one assertion that checks that createOrder() returns an object with status equal to 'pending', an id that is any string, and an items array that includes { sku: 'pen', qty: 1 }, while ignoring any other properties.
Show answer
expect(createOrder()).toMatchObject({ status: 'pending', id: expect.any(String), items: expect.arrayContaining([{ sku: 'pen', qty: 1 }]) }). toMatchObject ignores extra properties, expect.any(String) accepts any generated id, and arrayContaining checks that the item is present with deep equality without requiring the array to have only that item.