Vitest is a fast, modern unit testing framework powered by Vite, designed primarily for JavaScript and TypeScript projects.
npm install -D vitest @vitest/ui jsdom
package.json file "scripts": {
"test": "vitest",
"test:ui": "vitest --ui",
"test:run": "vitest run"
}
mkdir tests
touch function.js
export default function calculateSquare(number) {
return number * number;
}
touch tests/function.test.js
import { describe, it, expect } from "vitest";
import calculateSquare from "../function.js";
describe("calculateSquare", () => {
it("returns the correct value", () => {
const result = calculateSquare(2);
expect(result).toBe(4);
})
})
npm run test
npm run test:ui
import { describe, it, expect, vi } from "vitest";
describe('broad overview of tests', () => {
// ...
})
it('test for a specific thing or behavior', () => {
// ...
expect(true).toBe(true);
})
it('test for a specific thing or behavior async', async () => {
// ...
expect(true).toBe(true);
})
expect().toBe(); // value
expect().toEqual(); // value
expect().toMatch();
expect().toContain();
expect().toBeNull();
expect().toBeCloseTo();
expect().not.toBe();
// Mocks
expect().toHaveBeenCalled();
expect().toHaveBeenCalledWith(); // argument
expect().toHaveReturned(); // mock functions
beforeEach(() => {
// reset state before each test
});
beforeAll(() => {
// reset state before all tests
});
afterEach(() => {
// reset state after each test
});
afterAll(() => {
// reset state after all tests
});
vi.fn(); // create a mock function
it("mockFunction exists", () => {
let mockFn = vi.fn();
mockFn('Grant');
expect(mockFn).toHaveBeenCalled();
expect(mockFn).toHaveBeenCalledWith('Grant');
})
it("mockFunction returns a default value", () => {
const mockFn = vi.fn(() => 42);
const result = mockFn('Grant');
expect(result).toBe(42);
expect(mockFn).toHaveBeenCalledWith('Grant');
})
it("mockFunction returns a custom value", () => {
const mockFn = vi.fn((name) => `Hello, ${name}`);
const result = mockFn('Grant');
expect(mockFn).toHaveReturnedWith('Hello, Grant');
expect(result).toBe('Hello, Grant');
})
// Used to mock whole dependencies (imports and modules)
vi.mock()
vi.mock('./api', () => ({
fetchUser: vi.fn()
}));