Sub topic 3
Anatomy of a Vitest test
This chapter assumes you can run ng test with the Vitest runner, which the setup chapter covers. It also assumes you know basic TypeScript and Angular standalone components. Here you will learn how a Vitest test file is built, what the matchers do, and which mistakes cause most confusing failures. The examples use plain TypeScript, so you can focus on the test runner before components enter the picture.
The building blocks
A Vitest test file is an ordinary TypeScript module. It imports a few functions from vitest, then calls them at the top level to register tests. Four functions cover most files:
describe(name, fn)groups related tests under a name.it(name, fn)defines one test.testis an alias, and the two behave identically.expect(value)starts an assertion about a value.viis the helper object for mocks, spies, and fake timers.
The Angular unit-test builder does not inject these as globals, so import them explicitly:
import { describe, it, expect } from 'vitest';Explicit imports keep the types accurate and make it clear where each function comes from. Examples in this tutorial always import what they use.
A first complete test
This file tests a small pure function. It needs no Angular at all.
import { describe, it, expect } from 'vitest';
export function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
describe('clamp', () => {
it('returns the value when it is inside the range', () => {
expect(clamp(5, 0, 10)).toBe(5);
});
it('returns the minimum when the value is too small', () => {
expect(clamp(-3, 0, 10)).toBe(0);
});
it('returns the maximum when the value is too large', () => {
expect(clamp(42, 0, 10)).toBe(10);
});
});In a real project the function lives in its own file and the spec imports it. It is inlined here so the example runs as shown.
Vitest runs each it callback. A test passes if the callback finishes without throwing. A failed expect throws an error, which is how the failure is reported. A test with no assertions also passes, which is a common source of false confidence.
How a test file executes
Vitest runs in two phases. During the collection phase it executes the file from top to bottom. Every describe callback runs immediately, and every it call registers a test without running its body. During the run phase, Vitest executes the registered tests in order.
This has a practical consequence. Code placed directly inside a describe body runs once, at collection time. Code inside an it body runs when that test runs. If you create state in a describe body, all tests share it.
import { describe, it, expect } from 'vitest';
describe('shared state trap', () => {
const items: string[] = []; // created once, at collection time
it('adds an item', () => {
items.push('a');
expect(items).toHaveLength(1);
});
it('sees the item from the previous test', () => {
expect(items).toHaveLength(1); // passes only because of the earlier test
});
});The second test passes only because the first one ran before it. Reorder or filter the tests and it fails. The fix is to create fresh state per test, using the hooks below.
Setup and teardown hooks
Hooks run code around your tests. Import them from vitest like the other functions.
| Hook | Runs | Typical use |
|---|---|---|
| `beforeEach` | Before every test in its scope | Build fresh objects, configure mocks |
| `afterEach` | After every test in its scope | Restore timers, clean up |
| `beforeAll` | Once before the first test in its scope | Expensive shared setup |
| `afterAll` | Once after the last test in its scope | Release shared resources |
Hooks apply to the describe block that contains them, and to nested blocks. Outer beforeEach hooks run before inner ones. afterEach hooks run in the reverse order for each test.
import { beforeEach, describe, it, expect } from 'vitest';
class Cart {
private readonly items: string[] = [];
add(item: string) {
this.items.push(item);
}
get size() {
return this.items.length;
}
}
describe('Cart', () => {
let cart: Cart;
beforeEach(() => {
cart = new Cart(); // a new cart for every test
});
it('starts empty', () => {
expect(cart.size).toBe(0);
});
it('counts added items', () => {
cart.add('book');
expect(cart.size).toBe(1);
});
});Declaring the variable with let in the describe scope and assigning it in beforeEach is the standard pattern. Every test then starts from the same clean state, no matter the order.
Later chapters rely on this. Angular's TestBed resets itself between tests, but your own mocks, timers, and variables do not, so you reset them in hooks.
Matchers
expect(value) returns an object of matchers. Each matcher compares the value to an expectation and throws if they do not match. The most useful ones follow.
| Matcher | Checks | Example |
|---|---|---|
| `toBe` | Identity, using `Object.is` | `expect(2 + 2).toBe(4)` |
| `toEqual` | Deep equality, ignoring `undefined` properties | `expect({ a: 1 }).toEqual({ a: 1 })` |
| `toStrictEqual` | Deep equality including `undefined` properties and class types | `expect(new Foo()).toStrictEqual(new Foo())` |
| `toBeTruthy`, `toBeFalsy` | Truthiness | `expect('x').toBeTruthy()` |
| `toBeNull`, `toBeUndefined`, `toBeDefined` | Specific empty values | `expect(null).toBeNull()` |
| `toContain` | An item in an array or a substring | `expect('Count: 5').toContain('5')` |
| `toHaveLength` | Array or string length | `expect([1, 2]).toHaveLength(2)` |
| `toThrow` | A function throws | `expect(() => fn()).toThrow('bad')` |
| `toHaveBeenCalledWith` | A mock received these arguments | `expect(spy).toHaveBeenCalledWith(5)` |
toBe versus toEqual
The most common matcher mistake is using toBe on objects. toBe checks that both sides are the very same reference, so two objects with identical contents fail it.
import { describe, it, expect } from 'vitest';
describe('equality', () => {
it('compares references with toBe', () => {
expect({ id: 1 }).not.toBe({ id: 1 });
});
it('compares contents with toEqual', () => {
expect({ id: 1 }).toEqual({ id: 1 });
});
it('distinguishes undefined properties with toStrictEqual', () => {
expect({ id: 1, note: undefined }).toEqual({ id: 1 });
expect({ id: 1, note: undefined }).not.toStrictEqual({ id: 1 });
});
});Use toBe for primitives and for checking that you got the same object back. Use toEqual for data.
Negation and asymmetric matchers
Put .not before a matcher to invert it, as in expect(list).not.toContain('x'). When you only care about part of a value, asymmetric matchers help:
import { describe, it, expect } from 'vitest';
describe('partial matching', () => {
it('matches only the fields you name', () => {
const user = { id: 7, name: 'Ada', createdAt: new Date() };
expect(user).toEqual(
expect.objectContaining({ id: 7, name: 'Ada' }),
);
});
});expect.objectContaining ignores the other properties. Without it, you would have to assert the unpredictable createdAt too.
Asserting on text from the DOM
Rendered text often carries extra whitespace. toContain on a substring is more stable than toBe on the full string. When you compare whole strings, call .trim() first. You will use this when reading textContent in the DOM chapters.
Writing good test names
A test name is the first thing you read when it fails, so make it say what the behavior is. A reliable shape is "does X when Y".
- Weak:
it('works') - Better:
it('returns the minimum when the value is too small')
Nest describe blocks when a component has distinct states. The reported name is the whole path, such as Cart > when empty > shows a hint. That path should read like a sentence.
Async tests
A test callback can be async, or it can return a promise. Vitest waits for the promise to settle. If the callback is not async and you start asynchronous work without waiting, the test finishes before the work does.
import { describe, it, expect } from 'vitest';
function delayedDouble(n: number): Promise<number> {
return Promise.resolve(n * 2);
}
describe('delayedDouble', () => {
it('resolves with the doubled value', async () => {
const result = await delayedDouble(4);
expect(result).toBe(8);
});
it('works with resolves too', async () => {
await expect(delayedDouble(4)).resolves.toBe(8);
});
});Always await an expect(...).resolves or .rejects assertion. If you forget, the assertion runs after the test ends, and a failure may go unreported or surface in the wrong test.
Controlling which tests run
While you work, you can narrow a run without editing the config:
it.only(...)anddescribe.only(...)run only the marked tests in that file.it.skip(...)anddescribe.skip(...)skip tests but still list them as skipped.it.todo('name')records a planned test with no body.
Remove every .only before committing, since it silently hides the rest of the file's tests. Skipped tests are better than commented-out ones because the report keeps reminding you they exist.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `describe is not defined` | The function was not imported from `vitest` | Add the import |
| `toBe` fails on equal-looking objects | `toBe` compares references | Use `toEqual` |
| A test passes alone but fails in the full run | State shared through a `describe` body or `beforeAll` | Create state in `beforeEach` |
| A failing assertion is never reported | A promise was not awaited | Make the test `async` and `await` it |
| Other tests are skipped unexpectedly | A leftover `.only` | Remove it |
Exercises
Exercise
A spec declares const items: string[] = [] inside a describe body, and each it pushes one string and checks items.length. The second test passes in a full run but fails when you run it alone with it.only. Why, and how do you fix it?
Show answer
The array is created once at collection time, so all tests share it. The second test only passes because the first test already pushed an item. Declare let items: string[] in the describe scope and assign items = [] in a beforeEach hook, so every test starts with a fresh array.
Exercise
You compare expect(getUser()).toBe({ id: 1, name: 'Ada' }) and the test fails even though getUser() returns an object with those same values. Which matcher should you use, and why?
Show answer
Use toEqual. toBe uses Object.is, which compares references, so two separately created objects never match. toEqual compares the contents deeply.