You change the multiply function a little. Then you open the console and type add(2, 3) and multiply(3, 4), one at a time, to make sure the results are still right. Tomorrow you change it again, and type the same things again. A program can do the checks you repeat every time the code changes.
That program is called a test runner, and Vitest is one of them. Vitest finds your test files, runs every test in them, then reports which passed and which failed. Picture a teacher marking an exam with an answer key. Each question is checked against the key, the right answers are counted, and the score goes in the corner of the paper. In this picture, the teacher is Vitest. The student's answer is your code's result, and the answer key is the value you expect. describe is one section of the exam (Maths, for example), it is one question, and expect(...).toBe(...) is checking one answer against the key.
A test runner is simpler than it sounds
Before using Vitest, look at what a test runner does. Below is a home-made test runner: two functions to test, add and multiply, then runTests, which checks them:
function add(a, b) {
return a + b;
}
function multiply(a, b) {
return a * b;
}
function runTests() {
let passed = 0;
if (add(2, 3) === 5) passed++;
if (multiply(3, 4) === 12) passed++;
if (add(-1, 1) === 0) passed++;
return passed;
}
console.log(runTests()); // 3
- Each
ifline is one check. It runs one function (addormultiply), then compares its result with the right answer. passed++only runs when the result matches. Sopassedcounts the checks that passed, not all the checks that ran.- If the body of
multiplyis mistyped asa + b,multiply(3, 4)gives 7, that check does not pass, andrunTests()returns 2.
Vitest does the same. It also gives every check a name, runs every test file, and shows exactly which check failed.
Install and run Vitest
Install Vitest in your project with npm:
npm install -D vitest
Vitest knows a test file by its name: a file whose name ends in .test.js or .spec.js (also .ts, .jsx, .tsx). There are two ways to run it:
npx vitest: watch mode. The tests run, then Vitest waits. Every time you save a file, the tests related to that file run again automatically. This is the default when you run Vitest in your own terminal.npx vitest run: runs once and exits. This command is used in CI (a server that runs the tests on every push). In CI, evennpx vitestruns only once.
Both commands usually go into package.json as "test": "vitest" and "test:run": "vitest run".
Writing your first test
This is the test file math.test.js for add and multiply, which it imports from math.js:
// math.test.js
import { describe, it, expect } from "vitest";
import { add, multiply } from "./math.js";
describe("math", () => {
it("adds two numbers", () => {
expect(add(2, 3)).toBe(5);
});
it("multiplies two numbers", () => {
expect(multiply(3, 4)).toBe(12);
});
});
import { describe, it, expect } from "vitest"takes the test functions from Vitest. In the exercises, the editor already has these functions without an import.describe("math", ...)groups related tests.it("...", ...)defines one test.test(...)is exactly the same asit(...).expect(multiply(3, 4)).toBe(12)checks the result ofmultiply(3, 4)withtoBe.toBecompares like===.
Suppose the body of multiply is mistyped as a + b. Run npx vitest run --reporter=verbose. The --reporter=verbose option always lists every test, the passing ones too. Vitest prints:
✓ math.test.js > math > adds two numbers 1ms
× math.test.js > math > multiplies two numbers 3ms
→ expected 7 to be 12 // Object.is equality
Test Files 1 failed (1)
Tests 1 failed | 1 passed (2)
A ✓ means the test passed, and × means it failed. How to read the message: expected 7 to be 12 means your code gave 7, while the test expected 12. The first number is always what your code produced.
To test many input pairs with the same test, use it.each. Don't copy it again and again. Write this code inside describe("math", ...):
it.each([
[2, 3, 6],
[5, 0, 0],
[-2, 4, -8],
])("multiply(%i, %i) = %i", (a, b, expected) => {
expect(multiply(a, b)).toBe(expected);
});
Each row of the array becomes one test. The values in that row go into the parameters a, b and expected, in order. Each %i in the test name is replaced by a number from that row, also in order. With --reporter=verbose, Vitest prints three ✓: math > multiply(2, 3) = 6, math > multiply(5, 0) = 0 and math > multiply(-2, 4) = -8.
beforeEach: every test starts from zero
In the code below, increment adds one to counter, and beforeEach sets counter back to 0 before each test:
let counter = 0;
function increment() {
counter++;
}
describe("increment", () => {
beforeEach(() => {
counter = 0; // runs before EVERY test in this block
});
it("increments the counter once", () => {
increment();
expect(counter).toBe(1);
});
it("starts from 0 again, not from the previous test", () => {
increment();
increment();
expect(counter).toBe(2);
});
});
Before you look at the table below, guess: if that beforeEach block is removed, does the second test pass or fail?
| When | No reset | With beforeEach |
|---|---|---|
| Test 1 starts | counter 0 |
counter 0 |
| Test 1 ends | 1, passes | 1, passes |
| Test 2 starts | 1, left over from test 1 | 0, reset |
| Test 2 ends | 3, fails: expected 3 to be 2 |
2, passes |
Without a reset, the second test fails, because counter still holds the 1 from the first test.
There are four hooks (functions Vitest runs before or after your tests):
beforeEach: before every test. The most used one, to set up a clean state.afterEach: after every test.beforeAll: once, before all the tests in thatdescribeblock.afterAll: once, after all the tests are done. Good for cleaning up, such as closing the database connection withdb.disconnect().
⚠️ Small slips in your first test file
- Resetting with
beforeAll.beforeAllruns only once, so the second test still sees what the first left behind. To reset before each test, usebeforeEach. - Misreading the error. In
expected 7 to be 12, 7 is what your code gave and 12 is the value the test expected. - Forgetting the import. Without
import { describe, it, expect } from "vitest", the test file fails before a single test runs:ReferenceError: describe is not defined. The exception is a Vitest config with theglobals: trueoption. - Checking a number you typed yourself. What goes into
expectmust be your code's result:expect(multiply(3, 4))orexpect(counter), notexpect(12).
TL;DR: Vitest is a test runner: a program that runs every test in your .test.js files, then reports which passed and which failed. describe groups tests, it (or test) is one test, and expect(result).toBe(expected) compares your code's result with the value you expect. npx vitest runs in watch mode: the tests run again every time you save a file. npx vitest run runs once and exits. In the failure message expected 7 to be 12, the first number is your code's result. beforeEach runs before every test, so use beforeEach to set variables back to their starting values. afterEach runs after every test, while beforeAll and afterAll run only once, before and after all the tests.
⚡ Your first Vitest test
Write:
import { describe, it, expect } from "vitest";
import { add, multiply } from "./math.js";
describe("math", () => {
it("multiplies two numbers", () => {
expect(multiply(3, 4)).toBe(12);
});
});
Meaning: Vitest is a test runner: a program that runs tests, then reports which passed and which failed. multiply is a function, imported from math.js, that multiplies two numbers. describe groups tests, and it is one test. expect(...) keeps the result of multiply(3, 4), then toBe(12) compares it with 12, like ===. Vitest knows a test file by its name: one that ends in .test.js or .spec.js.
⚡ npx vitest or npx vitest run
Write:
npx vitest
npx vitest run
Guess first: which command keeps running and runs the tests again every time you save a file?
npx vitest. That way of running is called watch mode, and it is the default when you run Vitest in your own terminal.
Meaning: npx vitest run runs once and exits. That is the command used in CI (a server that runs the tests on every push).
⚡ Reading a failure
Guess first: the test checks expect(multiply(3, 4)).toBe(12), and Vitest reports expected 7 to be 12. Which number came from your code?
7 is from your code, and 12 is what the test expected. The first number is always your code's result.
Meaning: The 7 appears when the body of multiply is mistyped as a + b (plus, not times): multiply(3, 4) gives 7. Vitest marks a failed test with ×, and a passed test with ✓.
⚡ beforeEach: every test starts from zero
Write:
beforeEach(() => {
counter = 0; // runs before EVERY test in this block
});
Meaning: counter is a variable that goes up by one each time a test calls increment(). beforeEach runs before every test in the same describe block and sets counter back to 0. So each test starts from zero, not from what the test before left behind. beforeAll runs only once, so it can't reset before each test.