Vitest

Vitest is a fast, modern unit testing framework powered by Vite, designed primarily for JavaScript and TypeScript projects.

Vitest Basics

Install Vitest

Install Vitest

npm install -D vitest @vitest/ui jsdom
  • vitest → the test runner
  • @vitest/ui → optional browser UI for tests
  • jsdom → simulates a browser environment for React

Update the package.json file

"scripts": {
  "test": "vitest",
  "test:ui": "vitest --ui",
  "test:run": "vitest run"
}

Create a Test

Create the test folder

mkdir tests

Create a function to test

touch function.js
export default function calculateSquare(number) {
  return number * number;
}

Create a simple test

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);
  })
})

Run Vitest

npm run test
npm run test:ui

Basic Tests

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

Before & After Each/All

beforeEach(() => {
  // reset state before each test
});
beforeAll(() => {
  // reset state before all tests
});
afterEach(() => {
  // reset state after each test
});
afterAll(() => {
  // reset state after all tests
});

Mocks

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()
}));