Vitest for Beginners: Write a First Useful Unit Test
Set up Vitest in a practice JavaScript project, test normal and boundary cases, read a deliberate failure, and run a one-shot check before committing.
By Velloreth
The first useful unit test is small enough that you can explain why it should pass and what would make it fail. Vitest provides a test runner and assertions for JavaScript projects, with a development workflow that can rerun tests as files change.
This tutorial tests a pure function for a reading-session app. There is no browser, database, external service, or UI framework. Keeping those dependencies out of the first exercise makes a failure easier to understand.
Why this is a timely tool to learn
Vitest appears in the 2026 Stack Overflow testing-tool usage table. That supports its relevance to current JavaScript work, but it does not make switching runners mandatory. A project with an effective existing test suite may benefit more from better cases than from a new tool.
The unit-testing basics guide explains the general idea. This article adds a concrete runner setup, a deliberately broken implementation, and a repeatable command you can use before a commit.
Check compatibility and create a project
Use a Node release supported by the version of Vitest you install. The official getting-started page checked for this article lists Node 22.12 or newer and Vite 6.4 or newer for its current release. Those are version-sensitive requirements, so read that page again when installing later.
In a new practice directory:
npm init -y
npm install -D vitest
Keep the generated lockfile. For this tutorial, use JavaScript modules. Add "type": "module" and the following scripts to the existing package.json, preserving its other fields:
{
"type": "module",
"scripts": {
"test": "vitest",
"test:run": "vitest run"
}
}
That snippet shows the relevant fields, not a requirement to overwrite a real application’s entire package file. In an existing Vite project, inspect its test setup before adding a second configuration.
Write a function with a clear boundary
Save this as session.js:
export function validMinutes(minutes) {
return Number.isInteger(minutes) && minutes >= 1 && minutes <= 180;
}
The function accepts whole-number durations between one and 180. Its return value is a Boolean. The range is a practice-app rule, not a standard for all session timers.
Now create session.test.js beside it:
import { expect, test } from 'vitest';
import { validMinutes } from './session.js';
test('accepts an ordinary session', () => {
expect(validMinutes(25)).toBe(true);
});
test('accepts both boundaries', () => {
expect(validMinutes(1)).toBe(true);
expect(validMinutes(180)).toBe(true);
});
test('rejects values outside the contract', () => {
expect(validMinutes(0)).toBe(false);
expect(validMinutes(181)).toBe(false);
expect(validMinutes(2.5)).toBe(false);
expect(validMinutes('25')).toBe(false);
});
The .test. portion of the filename follows the runner’s default discovery convention. Each name describes behavior rather than the internal comparison operators. That makes the suite readable when someone sees only the test output.
Run once, then try watch mode
For one run:
npm run test:run
For a development session:
npm test
Watch mode is useful while editing, but it can look like a command that never finished if you expected a one-shot check. Use the explicit run command in automation and before reporting that a suite completed.
Read the counts and failures rather than treating any terminal output as success. A command that discovers zero tests has not verified the examples you intended. Confirm that session.test.js is listed and that the expected tests ran.
Prove the test can catch a mistake
Temporarily change the final comparison to minutes < 180. The boundary test should fail because 180 is supposed to be accepted. Inspect the actual and expected values, then restore the correct comparison.
This deliberate failure checks the test’s usefulness. If it stays green, you may be running a different file, checking the wrong behavior, or using an assertion that never observes the changed result. A test must be connected to the implementation it claims to cover.
Do not change expectations merely to match broken code. When requirements change, update the contract and explain why. The regression-testing guide describes how a real bug can become a permanent test case.
Avoid early testing traps
Do not add a network request to make the first example feel more realistic. Network access introduces credentials, latency, and service availability that distract from the assertion. Start with pure logic and add integration coverage when a real boundary requires it.
Do not chase a coverage percentage before checking important outcomes. A test can execute a line without verifying what matters about it. The site’s coverage guide explains that coverage measures execution, not complete correctness.
If you later test TypeScript code, keep a separate type-check command. A passing runtime test does not prove that all source files satisfy the compiler’s type rules. Similarly, this Node-only example does not test layout, keyboard interaction, or browser compatibility.
A practical next step
Take one small function from a personal project and write its contract in plain language. Choose an ordinary case, a boundary, and a rejected input. Run the suite once and introduce a temporary mistake to see whether the intended test catches it.
Keep that change separate from a large refactor. A small, understandable test suite gives you a safer place to start improving behavior. Add more cases when they explain a real distinction, not merely because adding test lines feels productive.
Troubleshoot discovery before changing assertions
If no tests run, confirm the working directory, filename, and package script. Check whether an existing configuration includes a narrower folder pattern. If the import fails, verify that the relative path and extension match the saved file. These are setup failures, not evidence that the function’s boundary logic is wrong.
If a suite passes too quickly to look plausible, read the discovered test count. Temporarily place a deliberate failing assertion in the expected file and rerun the exact command. Remove it after confirming the connection. This short check is useful when moving a test into a monorepo or adding a new CI script, where it is easy to run the right command in the wrong package.
Sources and scope
Checked October 26, 2026. Setup and command behavior follow the official Vitest getting-started guide. Current-use context comes from the 2026 Stack Overflow technology data. Requirements can change with the installed release; this is not a universal version-compatibility promise.