Unit tests with Vitest
Test utilities and hooks with fast unit tests.
By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.
In short
Unit tests check small pieces of logic, like utilities and hooks, in isolation. Vitest runs them fast with a Jest-compatible API and re-runs affected tests as you save.
Explained simply
A unit test is a tiny program that checks one small piece of your code. You give a function some input and check that the output is what you expect. If someone breaks that function later, the test fails and tells them right away.
Vitest is a test runner for JavaScript and TypeScript projects. It finds your test files, runs them very fast and shows which checks passed. In watch mode it re-runs only the tests affected by the file you just saved, so you get feedback in about a second.
Some code depends on things that are slow or unpredictable: the network, the clock, random numbers. In tests you replace these with fakes called mocks. A mock returns exactly what you tell it to, and it records how it was called.
Unit tests are cheap to write and fast to run, so you can have hundreds of them. They are best for logic: formatting, validation, calculations and custom React hooks. Whole pages and user flows are better covered by component and end-to-end tests.
Press Play on a diagram to walk through it one step at a time.
- Step 1Arrange
Set up inputs, mocks and fake timers
- Step 2Act
Call the function or hook under test
- Step 3Assert
Check the result with expect
- Step 4Clean up
Restore mocks and real timers
- 1E2E (Playwright)
A few critical flows in a real browser
- 2Component (Testing Library)
Components as users see them
- 3Unit (Vitest)
Many fast tests for logic and hooks
- 4Static checks
TypeScript and ESLint catch typos for free
In depth
Setting up Vitest in a React or Next.js project
Install it with npm install -D vitest. For React components and hooks you also need a simulated browser DOM, so add jsdom (or happy-dom), @vitejs/plugin-react and the Testing Library packages. Create vitest.config.ts with defineConfig from vitest/config, add the React plugin, and set test.environment to "jsdom". A setupFiles entry runs before every test file, which is where you import @testing-library/jest-dom/vitest for matchers like toBeInTheDocument.
Add "test": "vitest" to package.json scripts. npm test then starts watch mode on your machine, while vitest run (or any environment where the CI variable is set) runs once and exits with a non-zero code on failure. Vitest finds files ending in .test.ts, .spec.ts and their tsx versions. Set globals: true if you want describe, it and expect without imports; otherwise import them from vitest, which keeps types explicit.
- npx vitest run src/utils runs only tests under that folder
- npx vitest -t "slugify" runs tests whose name matches
- npx vitest run --coverage with @vitest/coverage-v8 installed
Writing good tests for pure functions
A pure function always returns the same output for the same input and changes nothing outside itself. That makes it ideal for unit tests: no setup, no cleanup. Cover the normal case, then the edges: empty strings and arrays, zero and negative numbers, very long input, unusual characters, and values exactly on a boundary such as a 10-character limit.
Choose the right matcher. toBe compares with Object.is, so use it for numbers, strings and booleans. toEqual compares objects and arrays by their contents; toStrictEqual also checks undefined properties and class types. For errors, wrap the call: expect(() => parse("")).toThrow("empty"). For promises, use await expect(load()).resolves.toEqual(...) or .rejects.toThrow(). test.each takes a table of cases and creates one test per row, which keeps edge cases visible and cheap to add.
- expect(0.1 + 0.2).toBeCloseTo(0.3) for floating point
- expect(list).toContain("a") and expect(obj).toMatchObject({ id: 1 })
- it.each([[1, "1st"], [2, "2nd"]])("ordinal(%i)", ...)
Testing custom hooks with renderHook
Hooks can only run inside a React component, so Testing Library provides renderHook. It renders a tiny invisible component that calls your hook and gives you result.current, the latest value the hook returned. To pass new arguments, call rerender with new props, which simulates the parent component re-rendering.
When your test triggers a state update directly, for example by calling a function returned from the hook or by advancing fake timers, wrap it in act(). act tells React to process the update and re-render before your next line runs, so result.current is fresh. Read result.current after the update, not before: if you save it in a variable early, you keep the old value. Hooks that need a context provider (a theme, a router, a query client) take a wrapper option, a component that renders the providers around the hook.
- Test to renderHook: renderHook(() => useCounter(5))1renderHook(() => useCounter(5))
- renderHook to useCounter: Call hook inside a test component2Call hook inside a test component
- useCounter to renderHook: Return { count: 5, increment }3Return { count: 5, increment }
- Test to useCounter: act(() => result.current.increment())4act(() => result.current.increment())
- useCounter to renderHook: Re-render, return { count: 6 }5Re-render, return { count: 6 }
- Test to renderHook: expect(result.current.count).toBe(6)6expect(result.current.count).toBe(6)
Mocks, spies and fake timers
vi.fn() creates a fake function that records every call; check it with toHaveBeenCalledWith or toHaveBeenCalledTimes. vi.spyOn(object, "method") wraps a real method so you can watch it or replace its result with mockReturnValue or mockResolvedValue. vi.mock("./api") replaces a whole module for this test file. Vitest hoists vi.mock calls to the top of the file, before imports, so the code under test receives the fake. Use vi.mocked(fn) to get proper TypeScript types on a mocked import.
vi.useFakeTimers() swaps setTimeout, setInterval and Date for controllable versions. vi.advanceTimersByTime(300) jumps 300 ms instantly, vi.runAllTimers() runs everything pending, and vi.setSystemTime(new Date("2026-01-01")) fixes the clock. Always undo fakes in afterEach (vi.useRealTimers(), vi.restoreAllMocks()), or enable restoreMocks in the config, so one test cannot leak into the next.
- A brand-new fake function
- Pass it as a callback prop
- Records calls and arguments
- Wraps an existing method
- Can keep or replace the real behaviour
- Restore with mockRestore()
- Replaces a whole module
- Hoisted above imports
- Good for API clients
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Set up Vitest~45m
- 2Test pure utility functions~45m
- 3Test custom hooks~45m
- 4Mock modules and timers~45m
Key points
- Pure functions are the easiest and most valuable things to unit test.
- Test behaviour and edge cases, such as empty input and boundaries.
- vi.mock replaces a module, and vi.useFakeTimers controls time.
- Test hooks with renderHook from Testing Library.
Key terms
Tap a card to flip it. 0/5 known
Examples
import { describe, it, expect } from 'vitest';
export function slugify(s: string) {
return s.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
}
describe('slugify', () => {
it('lowercases and joins words', () => {
expect(slugify('Hello World')).toBe('hello-world');
});
it('strips symbols and edges', () => {
expect(slugify(' React & Next! ')).toBe('react-next');
});
});Two focused tests for a pure utility.
Testing a debounce hook with fake timers
useDebounce(value, 300) should return the old value until 300 ms pass without a change. Step 1: switch to fake timers before each test. Step 2: renderHook with initialProps so the value can change. Step 3: rerender with a new value and check the old one is still returned. Step 4: advance time inside act and check the new value appears.
import { renderHook, act } from '@testing-library/react';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { useDebounce } from './useDebounce';
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
it('updates only after the delay', () => {
const { result, rerender } = renderHook(({ v }) => useDebounce(v, 300), { initialProps: { v: 'a' } });
rerender({ v: 'ab' });
expect(result.current).toBe('a');
act(() => vi.advanceTimersByTime(300));
expect(result.current).toBe('ab');
});Mocking an API module
getGreeting(id) calls fetchUser from ./api and builds a sentence. The test must not hit the network. Step 1: vi.mock replaces ./api with an object whose fetchUser is a vi.fn. Step 2: vi.mocked gives it types, and mockResolvedValue sets what the promise returns. Step 3: assert on the result with resolves. Step 4: check the mock was called with the right id.
import { expect, it, vi } from 'vitest';
import { fetchUser } from './api';
import { getGreeting } from './greeting';
vi.mock('./api', () => ({ fetchUser: vi.fn() }));
it('greets the user by name', async () => {
vi.mocked(fetchUser).mockResolvedValue({ id: '1', name: 'Asha' });
await expect(getGreeting('1')).resolves.toBe('Hello, Asha!');
expect(fetchUser).toHaveBeenCalledWith('1');
});Quick reference
- npm install -D vitest jsdom @vitejs/plugin-react @testing-library/react
- vitest = watch mode; vitest run = run once (use in CI)
- toBe for primitives, toEqual for objects and arrays, toThrow for errors
- await expect(promise).resolves.toEqual(x) / .rejects.toThrow()
- vi.fn(), vi.spyOn(obj, "m"), vi.mock("./module") (hoisted)
- vi.useFakeTimers(); vi.advanceTimersByTime(ms); vi.useRealTimers()
- renderHook(() => useX()) then read result.current after act()
- Restore mocks in afterEach or set restoreMocks: true in the config
Common mistakes
- Testing implementation details that break on every refactor.
- Forgetting to restore mocks, so one test affects another.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write tests for formatPrice(cents: number) that returns strings like $12.50, covering 0, 5 and 1250.
- Exercise 2medium
Test a useToggle(initial) hook that returns [value, toggle]: it starts with initial and flips on each toggle call.
- Exercise 3hard
isExpired(token) compares token.expiresAt (ms) with Date.now(). Test it at exactly the expiry moment and one millisecond after, without depending on the real clock.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Vitest or Jest for a new project?
- Vitest is the common choice for Vite and modern Next.js projects: it handles TypeScript and ES modules without extra setup and is very fast. Its API is close to Jest's, so most Jest knowledge carries over.
- Can I test async Server Components with Vitest?
- Not reliably today; the Next.js docs recommend end-to-end tests for async Server Components. Test their logic by moving it into plain functions you can unit test.
- Should I aim for 100 percent code coverage?
- No. Coverage shows which lines never ran, which is useful, but 100 percent does not mean the tests check the right things. Focus on logic that would hurt users if it broke.
- What is the difference between jsdom and happy-dom?
- Both simulate a browser DOM inside Node. jsdom is older and more complete; happy-dom is often faster but implements less. Start with jsdom unless speed becomes a problem.