How to Use Vitest for Unit Testing in JavaScript Projects
Vitest is a blazing-fast unit testing framework built on top of Vite. It offers native support for TypeScript, JSX, and modern JavaScript, making it an ideal choice for testing applications that already use Vite. This tutorial will walk you through setting up and writing your first tests with Vitest.
To get started, install Vitest as a development dependency using your package manager. For example, with npm: npm install -D vitest. If you’re using Vite, Vitest will automatically read your existing Vite configuration. For non-Vite projects, you can still use Vitest – it works out of the box with minimal setup.
Writing Your First Test
Create a file named sum.test.js (or .ts for TypeScript). Vitest uses a Jest-compatible API, so you can use describe, it, expect immediately. Here’s a simple example:
import { describe, it, expect } from 'vitest';
function sum(a, b) {
return a + b;
}
describe('sum function', () => {
it('adds two numbers correctly', () => {
expect(sum(1, 2)).toBe(3);
expect(sum(-1, 1)).toBe(0);
});
});
Running Tests
Add a test script to your package.json:
"scripts": {
"test": "vitest"
}
Then run npm test or npx vitest. Vitest will watch for file changes by default. To run once without watch mode, use vitest run.
Advanced Features
- Mocking: Use
vi.mock()to mock modules orvi.fn()for functions. - Coverage: Enable code coverage with
npm install -D @vitest/coverage-v8and runvitest --coverage. - Configuration: Create a
vitest.config.tsto customize test patterns, environment, or global setup.
Conclusion
Vitest provides a modern, fast, and developer-friendly experience for unit testing. Its seamless integration with Vite, familiar Jest API, and built-in TypeScript support make it a powerful choice for any JavaScript project. Start testing today and enjoy instant feedback with minimal configuration.