Vitest is a Vite-native testing framework that is compatible with Jest's API but runs 10-20x faster. It provides instant HMR, TypeScript support, and ESM-first testing.
Installation
npm install -D vitest
Basic Tests
// sum.test.ts
import { describe, it, expect } from "vitest";
import { sum, multiply } from "./math";
describe("math", () => {
it("adds numbers correctly", () => {
expect(sum(1, 2)).toBe(3);
expect(sum(-1, 1)).toBe(0);
});
it("multiplies numbers", () => {
expect(multiply(3, 4)).toBe(12);
});
});
Async Testing
import { describe, it, expect } from "vitest";
describe("API", () => {
it("fetches users", async () => {
const users = await fetchUsers();
expect(users).toHaveLength(10);
expect(users[0]).toHaveProperty("name");
});
it("handles errors", async () => {
await expect(fetchUser("invalid")).rejects.toThrow("Not found");
});
});
Mocking
import { vi, describe, it, expect } from "vitest";
// Mock a module
vi.mock("./database", () => ({
getUser: vi.fn().mockResolvedValue({ id: 1, name: "Test" })
}));
import { getUser } from "./database";
describe("with mocks", () => {
it("uses mocked database", async () => {
const user = await getUser(1);
expect(user.name).toBe("Test");
expect(getUser).toHaveBeenCalledWith(1);
});
});
// Spy on functions
const spy = vi.spyOn(console, "log");
console.log("test");
expect(spy).toHaveBeenCalledWith("test");
// Fake timers
vi.useFakeTimers();
setTimeout(() => callback(), 1000);
vi.advanceTimersByTime(1000);
expect(callback).toHaveBeenCalled();
Snapshot Testing
it("matches snapshot", () => {
const result = generateHTML({ title: "Test" });
expect(result).toMatchSnapshot();
});
it("matches inline snapshot", () => {
expect(formatDate(new Date(2026, 0, 1))).toMatchInlineSnapshot(`"January 1, 2026"`);
});
Configuration
// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
environment: "jsdom", // or "node"
coverage: {
provider: "v8",
reporter: ["text", "html"],
thresholds: { lines: 80, functions: 80 }
},
include: ["src/**/*.test.ts"]
}
});
vitest # Watch mode
vitest run # Single run
vitest --coverage # With coverage
Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.
Top comments (0)