Sub topic 2
Organizing Tests with describe, test, and it
This chapter assumes you already have Vitest installed and can run npx vitest from the previous chapter. You should also be comfortable with ES modules, arrow functions, and closures. The examples use toBe, toEqual, and toThrow. The next chapter covers matchers in detail, so here they only check results.
The goal of this chapter is to understand how Vitest finds your tests, how describe, test, and it fit together, and the order in which Vitest runs the code inside them. That order causes some of the most confusing bugs new users hit.
How Vitest finds test files
Vitest does not run every JavaScript file in your project. By default it collects files whose names match this glob:
**/*.{test,spec}.?(c|m)[jt]s?(x)So cart.test.js, cart.spec.ts, and Button.test.jsx are all picked up, and cart.js is not. It skips node_modules and a few other default folders. You can change the pattern with the include option, which the configuration chapter covers.
Two layouts are common:
| Layout | Example | Trade-off |
|---|---|---|
| Colocated | `src/cart.js` next to `src/cart.test.js` | Easy to find the test for a file; tests ship in the same folder as source |
| Separate folder | `src/cart.js` and `tests/cart.test.js` | Keeps `src` clean; import paths get longer |
Either one works. Choose one per project and use it everywhere.
test and it are the same function
test and it are aliases. Both take a name, a function, and an optional timeout:
import { test, it, expect } from 'vitest'
test('adds numbers', () => {
expect(1 + 1).toBe(2)
})
it('also adds numbers', () => {
expect(2 + 2).toBe(4)
})Most teams use it inside a describe block, because the name then reads as a sentence: "cart › it returns 0 for an empty cart". They use test for standalone tests at the top level of a file. Vitest doesn't care which one you call.
A test passes if its function returns, or if the promise it returns resolves, without throwing. A test fails if the function throws or the promise rejects. A failing expect works by throwing an error. So a test that contains no assertions at all passes, and that is easy to miss:
import { test } from 'vitest'
test('looks like it checks something', () => {
const result = 1 + 1
// No expect: this test always passes
})Grouping with describe
describe creates a suite, which is a named group of tests and other suites. Suites can nest. Every test's full name joins its suite titles to its own title, so test reports and failure messages show where each test belongs.
Here is a small module to test:
// cart.js
export function createCart() {
const items = new Map()
return {
addItem(name, price, quantity = 1) {
if (quantity <= 0) {
throw new Error('Quantity must be positive')
}
const existing = items.get(name)
if (existing) {
existing.quantity += quantity
} else {
items.set(name, { price, quantity })
}
},
removeItem(name) {
items.delete(name)
},
count() {
let total = 0
for (const item of items.values()) total += item.quantity
return total
},
total() {
let sum = 0
for (const item of items.values()) sum += item.price * item.quantity
return sum
},
}
}The tests below are grouped first by module, then by method:
// cart.test.js
import { describe, it, expect } from 'vitest'
import { createCart } from './cart.js'
describe('cart', () => {
describe('addItem', () => {
it('adds a new item', () => {
const cart = createCart()
cart.addItem('apple', 0.5)
expect(cart.count()).toBe(1)
})
it('increases the quantity of an existing item', () => {
const cart = createCart()
cart.addItem('apple', 0.5, 2)
cart.addItem('apple', 0.5, 3)
expect(cart.count()).toBe(5)
})
it('rejects a quantity of zero', () => {
const cart = createCart()
expect(() => cart.addItem('apple', 0.5, 0)).toThrow('Quantity must be positive')
})
})
describe('removeItem', () => {
it('removes an item completely', () => {
const cart = createCart()
cart.addItem('apple', 0.5, 4)
cart.removeItem('apple')
expect(cart.count()).toBe(0)
})
})
describe('total', () => {
it('returns 0 for an empty cart', () => {
expect(createCart().total()).toBe(0)
})
it('multiplies price by quantity', () => {
const cart = createCart()
cart.addItem('apple', 0.5, 4)
cart.addItem('pear', 1.25)
expect(cart.total()).toBe(3.25)
})
})
})Run it with the verbose reporter to see the full tree:
npx vitest run --reporter=verboseEach line shows a full name such as cart > addItem > rejects a quantity of zero. When a test fails, that full name tells you which unit and which behavior broke before you open the file. The -t filter matches against these full names too. The chapter on filtering covers that.
How deep to nest
One or two levels usually work best: the unit under test, then the method or scenario. If you have three or four levels, the full names get long and you have to scroll to find out which context a test is in. A useful check is to read the full name aloud. It should sound like a sentence about behavior, such as "cart total multiplies price by quantity".
Collection first, then execution
Vitest handles each test file in two phases:
- Collection. Vitest imports the file and runs each
describecallback right away. These callbacks only register tests and nested suites. They do not run the tests. - Execution. After collection, Vitest runs the registered tests one at a time, in the order they were defined.
You can watch this happen with a few console.log calls:
// order.test.js
import { describe, test } from 'vitest'
describe('outer', () => {
console.log('collect outer')
test('a', () => console.log('run a'))
describe('inner', () => {
console.log('collect inner')
test('b', () => console.log('run b'))
})
test('c', () => console.log('run c'))
})The output is:
collect outer
collect inner
run a
run b
run cBoth collect lines print before any run line. The tests then run in source order, a, b, c, even though b sits inside a nested suite.
The shared-state gotcha
Because describe bodies run during collection, any variable you create there is created once and then shared by every test in the suite:
import { describe, it, expect } from 'vitest'
import { createCart } from './cart.js'
describe('cart (fragile)', () => {
const cart = createCart() // created once, during collection
it('adds an item', () => {
cart.addItem('apple', 0.5)
expect(cart.count()).toBe(1)
})
it('starts empty', () => {
expect(cart.count()).toBe(0) // fails: the previous test left an apple in the cart
})
})The second test fails only because of the first one. If you run it alone it passes, and if you reorder the tests the results change. That is why the earlier cart tests each call createCart() themselves. Lifecycle hooks such as beforeEach handle this more cleanly. They get their own chapter later.
Keep describe callbacks synchronous
Collection expects each describe callback to register its tests and return. Don't await data in a describe body to decide which tests to define, and don't call expect there. A failure at that point happens during collection, so it gets reported as a suite or file error rather than as a test failure. Put async work inside tests, or in beforeAll when tests need to share it.
Timeouts
Each test has a default timeout of 5000 ms. If an async test is still running after that time, it fails. You can pass a different limit in milliseconds as the last argument:
import { test, expect } from 'vitest'
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
test('finishes a slow operation', async () => {
await wait(6000)
expect(true).toBe(true)
}, 10_000)Raise the timeout only for a test that really is slow. If a unit test needs more than a few seconds, it is usually waiting on something you should replace: a real network call, a real timer, or a real database. Later chapters on mocking and fake timers show how to replace them.
Importing versus globals
The examples here import describe, test, it, and expect from 'vitest'. This is the default, and it works with any editor and linter without extra setup. Vitest can also expose these functions as globals, as Jest does, through the globals: true option. The configuration chapter covers that option. Explicit imports keep each file self-describing, so this tutorial uses them.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| "No test files found" | File name doesn't match `*.test.js` / `*.spec.js` | Rename the file or adjust `include` |
| Test passes but checks nothing | No `expect` in the body | Add an assertion |
| Test passes alone, fails in the full file | State created in a `describe` body and mutated | Create state per test or in `beforeEach` |
| Setup code runs before any test, even for skipped ones | Work done in a `describe` body during collection | Move it into a test or hook |
| Async test fails with a timeout | Slow real dependency, or a promise that never settles | Mock the dependency; raise the timeout only when the test is legitimately slow |
Exercise
A file contains describe('A', () => { console.log('1'); test('x', () => console.log('2')); describe('B', () => { console.log('3'); test('y', () => console.log('4')) }) }). In what order do the numbers print, and why?
Show answer
1, 3, 2, 4. During collection Vitest runs both describe callbacks, which prints 1 and then 3. Only after collection does it run the tests in definition order: x prints 2, then y prints 4.
Exercise
In the fragile cart example, the test "starts empty" fails only when the full file runs. Explain the cause and give two ways to fix it using what this chapter covers.
Show answer
The cart is created once in the describe body during collection, so every test shares the same object, and "adds an item" leaves an apple in it. One fix is to call createCart() inside each test. Another is to reorder the tests, but that only hides the dependency between them. The proper fix is per-test state, either created inline or in a beforeEach hook (covered later).
Exercise
Write a describe block for an isEven(n) function with two nested groups, "with even numbers" and "with odd numbers", each with one it test. What full test names will the verbose reporter show?
Show answer
describe('isEven', () => { describe('with even numbers', () => { it('returns true for 4', () => { expect(isEven(4)).toBe(true) }) }); describe('with odd numbers', () => { it('returns false for 7', () => { expect(isEven(7)).toBe(false) }) }) }). The full names are "isEven > with even numbers > returns true for 4" and "isEven > with odd numbers > returns false for 7".