Writing Your First Vitest Test
What you'll learn: How to create a basic Vitest test file with the fundamental building blocks: describe, it/test, and expect.
Now that Vitest is configured, let's verify everything works by writing a simple test. Think of a test file as a science experiment—you set up conditions, perform an action, and check if the results match your hypothesis.
The Three Core Functions
Vitest gives you three essential functions to structure tests:
describe()– Groups related tests together (like a folder)it()ortest()– Defines a single test case (they're identical)expect()– Makes assertions about values (your "hypothesis check")
Your First Test File
Create a simple test to verify your setup works:
// src/utils/math.test.ts
import { describe, it, expect } from 'vitest';
describe('Basic Math Operations', () => {
it('should add two numbers correctly', () => {
const result = 2 + 2;
expect(result).toBe(4);
});
test('should multiply two numbers correctly', () => {
const result = 3 * 4;
expect(result).toBe(12);
});
});
The anatomy: describe creates a test suite named "Basic Math Operations." Inside, each it/test runs independently. The expect(result).toBe(4) line says "I expect this result to be exactly 4."
Run this with npm test or vitest in your terminal. You should see green checkmarks confirming both tests passed.
Why This Matters
This simple pattern—describe, test, expect—forms the foundation for every React component test you'll write. You're not testing React yet, just confirming Vitest executes tests and checks values correctly. Once this works, you've proven your testing environment is ready.
Key Takeaway: Every Vitest test uses describe() to group, it()/test() to define individual tests, and expect() to assert correctness—this trio verifies your testing setup before moving to React components.