Sub topic 3
Anatomy of a Vitest test
This chapter assumes you can read basic TypeScript and have run ng test as set up in the previous chapter. The examples use plain classes, so you can see the structure of a test before Angular enters the picture.
The three building blocks
A Vitest test file is built from three functions:
describegroups related tests under a name.itdefines one test.testis an alias with the same behavior.expectwraps a value and gives you matchers to check it.
The Angular CLI runner does not inject these as globals in the examples in this tutorial, so import them from vitest.
import { beforeEach, describe, it, expect } from 'vitest';
class Cart {
items: number[] = [];
add(price: number) {
if (price < 0) {
throw new Error('Price cannot be negative');
}
this.items.push(price);
}
total() {
return this.items.reduce((sum, price) => sum + price, 0);
}
}
describe('Cart', () => {
let cart: Cart;
beforeEach(() => {
cart = new Cart();
});
it('starts empty', () => {
expect(cart.total()).toBe(0);
});
it('sums the prices of added items', () => {
cart.add(10);
cart.add(5);
expect(cart.items).toEqual([10, 5]);
expect(cart.total()).toBe(15);
});
it('rejects negative prices', () => {
expect(() => cart.add(-1)).toThrow('Price cannot be negative');
});
});Arrange, act, assert
Each test follows the same three steps:
- Arrange: build the object under test and put it in the starting state.
- Act: do the one thing you want to check.
- Assert: compare the result with what you expect.
In the second test above, new Cart() is arranged by beforeEach, the two add calls are the act, and the expect lines are the assertions. Keeping one act per test makes a failure point at one behavior. The same shape applies later when the act is a button click on a component.
Hooks keep tests independent
beforeEach runs before every test in its describe block. afterEach runs after every test, even a failing one. Use them so no test depends on state left by another. Here every test gets a fresh Cart. If you created one Cart at the top of the describe and shared it, the order of the tests would change the results.
Common matchers
| Matcher | Checks | Example |
|---|---|---|
| `toBe` | Same value or same reference (`Object.is`) | `expect(total).toBe(15)` |
| `toEqual` | Deep equality of objects and arrays | `expect(items).toEqual([10, 5])` |
| `toContain` | Substring or array member | `expect(text).toContain('Count: 5')` |
| `toThrow` | A function throws | `expect(() => fn()).toThrow()` |
| `toHaveBeenCalledWith` | A mock received these arguments | `expect(spy).toHaveBeenCalledWith(5)` |
Add .not before the matcher to invert it, as in expect(spy).not.toHaveBeenCalled(). The last row uses a mock function, created with vi.fn(). You will use it heavily when you test outputs and replace services.
Common errors
- Using
toBeon objects.expect({ a: 1 }).toBe({ a: 1 })fails because the two literals are different references. UsetoEqual. - Passing the call instead of a function to
toThrow. Writeexpect(() => cart.add(-1)).toThrow(). If you writeexpect(cart.add(-1)).toThrow(), the error is thrown beforeexpectruns and the test fails with that error. - Leaving
it.onlyordescribe.onlyin a file. Vitest then skips every other test in that file, so the suite looks green while most of it never ran.it.skiphas the same risk. - Sharing mutable state between tests instead of resetting it in
beforeEach.
Exercise
A test contains expect(cart.items).toBe([10, 5]) after adding 10 and 5, and it fails even though the array contents are correct. Why does it fail, and how do you fix it?
Show answer
toBe compares references with Object.is, and the array literal in the assertion is a different object from cart.items. Change the matcher to toEqual, which compares the contents deeply.