Guide

Write a unit test with Vitest

A useful unit test checks a specific behavior through a small, repeatable example.

At a glance

Test declaration
test or it
Assertion entry point
expect

Overview

A useful unit test checks a specific behavior through a small, repeatable example. Vitest supplies a test runner and assertions, but the value of the test comes from choosing a case that would expose a meaningful mistake rather than merely restating the implementation.

1. Choose an observable behavior

Identify the input and expected result of a small unit. Include a meaningful boundary or failure case when it changes the contract, and avoid depending on unrelated network services or user-specific state.

2. Arrange, call, and assert

Set up the required data, call the unit, and assert the result through its public behavior. Keep the test readable enough that a failure explains what contract was broken.

3. Run the focused check

Run the relevant test file using the project's Vitest command. Confirm that a deliberately incorrect result would fail the assertion before relying on the test as evidence against regression.

Sources and review

MOOR's explanatory text is supported by the following source links.

  1. Getting started — Vitest
  2. Test API reference — Vitest

Browse MOOR Knowledge