Sub topic 1
Installing Vitest and Running Your First Test
Vitest is a unit testing framework for JavaScript and TypeScript, built on top of the Vite build tool. It runs test files through the same transform pipeline Vite uses. That means ES modules, TypeScript, and JSX work without a separate Babel or ts-jest setup. This chapter covers installing Vitest into a Node.js project, writing one small test file, and running it in watch mode and in single-run mode. It also explains how to read the output when a test passes and when it fails.
Prerequisites
This chapter assumes you can already do the following:
- Write modern JavaScript: ES module
import/export, arrow functions, and destructuring. - Read code that uses promises and
async/await. You will not need them until a later chapter. - Use npm, or another package manager such as pnpm or Yarn, to install packages and run
package.jsonscripts. - Run commands in a terminal.
You also need a current Node.js release. Recent Vitest versions require Node 20 or later, so check with node --version before you start. The commands below use npm. The pnpm and Yarn equivalents work the same way.
Setting Up the Project
Create a project and install Vitest
Start with an empty folder and create a package.json:
mkdir vitest-intro
cd vitest-intro
npm init -y
npm install --save-dev vitestInstall Vitest as a development dependency with --save-dev or -D. Your application never imports it at runtime, so it should stay out of production installs.
Opt into ES modules
Open package.json and add "type": "module". With this field, Node treats .js files as ES modules. Vitest transforms test files itself, but your own config files and any scripts you run directly with Node still follow this setting. Setting it now prevents confusing import errors later.
Then add two scripts:
{
"name": "vitest-intro",
"version": "1.0.0",
"type": "module",
"scripts": {
"test": "vitest",
"test:run": "vitest run"
},
"devDependencies": {
"vitest": "^4.0.0"
}
}Keep the version that npm actually wrote into your file. The ^4.0.0 above is only an example.
The test script starts Vitest in its default mode. The test:run script runs every test once and exits. The difference between the two is covered below.
Writing Your First Test File
How Vitest finds tests
You do not register test files anywhere. By default, Vitest collects every file whose name matches **/*.{test,spec}.?(c|m)[jt]s?(x). In practice, that means names like math.test.js, user.spec.ts, or Button.test.jsx. It skips node_modules and a few other folders such as .git. Most projects put each test file next to the module it tests.
The code under test and its test
Create math.js:
// math.js
export function add(a, b) {
return a + b
}
export function divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero')
}
return a / b
}Then create math.test.js next to it:
// math.test.js
import { describe, it, expect } from 'vitest'
import { add, divide } from './math.js'
describe('math', () => {
it('adds two numbers', () => {
expect(add(2, 3)).toBe(5)
})
it('throws when dividing by zero', () => {
expect(() => divide(1, 0)).toThrow('Cannot divide by zero')
})
it('compares objects by value with toEqual', () => {
expect({ total: add(1, 1) }).toEqual({ total: 2 })
})
})Each it call defines one test. A test is a name and a function. If the function returns without throwing, the test passes. describe groups related tests under a shared label. expect(value) wraps a value so you can check it with a matcher, a method such as toBe or toEqual. The next two chapters cover these functions in detail. For now, read each line as a statement that a value must equal another value or that a call must throw.
Note the first line. describe, it, and expect are imported explicitly from 'vitest'. Unlike Jest, Vitest does not inject globals by default.
Running Tests
Watch mode
Run:
npm testIn an interactive terminal, vitest starts in watch mode. It runs all tests, prints the results, and keeps running. When you save a file, Vitest uses Vite's module graph to work out which test files import that file, directly or indirectly, and reruns only those. If you edit math.js, math.test.js reruns. A test file that never imports math.js does not.
The output looks roughly like this:
✓ math.test.js (3 tests) 3ms
✓ math > adds two numbers
✓ math > throws when dividing by zero
✓ math > compares objects by value with toEqual
Test Files 1 passed (1)
Tests 3 passed (3)
Start at 10:44:12
Duration 210ms
PASS Waiting for file changes...
press h to show help, press q to quitThe exact layout depends on your Vitest version and reporter, but the parts are always the same. You get one line per file, test names prefixed with their describe labels, totals for files and tests, and timing.
While watch mode runs, single keys control it:
| Key | Action |
|---|---|
| `a` | Rerun all tests |
| `f` | Rerun only failed tests |
| `p` | Filter by file name pattern |
| `t` | Filter by test name pattern |
| `u` | Update failing snapshots |
| `h` | Show help |
| `q` | Quit |
Single-run mode
Run:
npm run test:runvitest run runs every test once, prints the summary, and exits. The exit code is 0 if everything passed and non-zero if anything failed, which is the signal CI systems and Git hooks check. You can also call it without a script: npx vitest run. The bare npx vitest uses the same default as npm test.
Vitest picks a mode automatically when you don't name one. If the terminal is not interactive, or the CI environment variable is set (most CI providers set it), plain vitest behaves like vitest run. A CI job that calls npm test will still exit instead of waiting for file changes. Naming the mode explicitly in scripts is still clearer to anyone reading package.json.
Passing a filter on the command line
Any extra argument is treated as a filter on file paths:
npx vitest run mathThis runs only test files whose path contains math. Filtering by test name and focusing tests with .only are covered in a later chapter.
Reading a Failure
To see a failure, change the expected value in the first test from 5 to 6 and save. Watch mode reruns the file and prints something like:
FAIL math.test.js > math > adds two numbers
AssertionError: expected 5 to be 6 // Object.is equality
- Expected
+ Received
- 6
+ 5
❯ math.test.js:6:23
4| describe('math', () => {
5| it('adds two numbers', () => {
6| expect(add(2, 3)).toBe(6)
| ^Read it from top to bottom:
- The header names the file and the full test path (
math > adds two numbers), so you can find the test even in a large suite. - The message names the matcher's rule.
toBeusesObject.is, which checks strict equality. - The diff shows the expected value with
-and the value your code produced with+. For objects and arrays, the diff marks only the lines that differ. - The code frame points at the exact line and column of the failed assertion.
Change the value back to 5 before you continue.
Common Setup Errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `No test files found, exiting with code 1` | File names don't match the pattern, such as `math-test.js` | Rename to `*.test.js` or `*.spec.js` |
| `describe is not defined` | Relying on Jest-style globals | Import from `'vitest'` or set `globals: true` |
| `Cannot use import statement outside a module` in a config or helper script | Node is loading the file as CommonJS | Add `"type": "module"` or use the `.mjs` extension |
| `npm test` never finishes in CI | The CI runner is not setting `CI` and appears interactive | Use `vitest run` in the CI script |
| An error saying the Node version is unsupported | Old Node.js | Upgrade to a supported LTS release |
Exercise
You add a file named stringUtils.tests.js containing valid tests, then run npx vitest run. Vitest reports "No test files found". Why, and what are two names that would work?
Show answer
The default include pattern matches .test. or .spec. followed by a JS or TS extension. .tests.js, with an extra "s", does not match. Rename it to stringUtils.test.js or stringUtils.spec.js, or change the include pattern in the config.
Exercise
A teammate's CI pipeline runs npm test, where the script is "test": "vitest". The job finishes correctly on GitHub Actions but hangs on a self-hosted runner. What explains the difference, and how would you fix it so it doesn't depend on the environment?
Show answer
Plain vitest uses watch mode when the terminal looks interactive and CI is not set. GitHub Actions sets CI=true, so Vitest runs once. The self-hosted runner probably doesn't set it, so Vitest waits for file changes. Use vitest run in the script CI calls, for example "test:run": "vitest run", so the run always exits with a pass or fail code.
Exercise
In watch mode, you edit math.js. Your project also has date.test.js, which imports only date.js. Which test files rerun, and why?
Show answer
Only math.test.js reruns. Vitest follows the module graph from the changed file to the test files that import it, directly or indirectly. date.test.js does not depend on math.js, so it is skipped. Press a to rerun everything.