Concept Explanation
Vitest is a modern testing framework designed for Vite. It is incredibly fast and uses the same syntax as the famous "Jest" framework, so your skills are transferable.
Syntax or Core Structure
A Simple Test
// math.js
export const add = (a, b) => a + b;
// math.test.js
import { expect, test } from 'vitest';
import { add } from './math';
test('adds 1 + 2 to equal 3', () => {
expect(add(1, 2)).toBe(3);
});
Technical Concept: Assertions
An Assertion is a claim. expect(result).toBe(10) is you claiming that the result will be 10. If it isn't, the test fails and tells you exactly what happened.
Common Matchers
expect(sum).toBe(5); // strict equality (numbers, strings)
expect(user).toEqual({ id: 1 }); // deep equality (objects, arrays)
expect(list).toContain("apple"); // array/string includes
expect(isReady).toBeTruthy(); // truthy check
expect(() => boom()).toThrow(); // expects a thrown error
Group related tests and share setup with describe and beforeEach:
describe("cart", () => {
let cart;
beforeEach(() => { cart = []; }); // fresh state per test
test("starts empty", () => expect(cart.length).toBe(0));
});
Common Mistakes
- toBe on Objects:
toBechecks reference identity — two identical objects aren'ttoBeequal. UsetoEqual. - No Isolation: Tests that share state fail randomly depending on order. Reset in
beforeEach. - One Giant Test: A test asserting ten things gives a vague failure. Prefer many small, focused tests.
Best Practices
- Arrange-Act-Assert: Structure each test in three clear steps.
- Test Behavior: Assert outputs, not internal calls, so refactors don't break tests.
- Watch Mode: Run
vitestin watch mode so tests re-run the instant you save.
Practice Exercises
- The Calculator: Write a
subtractfunction and a corresponding test in Vitest. - The Object Matcher: Use
.toEqual()to test if two objects have the same properties (Hint:.toBe()won't work for objects!). - The Async Test: Write a test for a function that returns a Promise using
async/awaitinside the test.