Popular Searches
Popular Course Categories
Popular Courses

Testing with Vitest

Testing with Vitest

React Testing and Debugging

Testing with Vitest in React

Testing is an important part of React development because it helps developers verify that components, functions, and user interactions work as expected. Vitest is a modern JavaScript testing framework powered by Vite. It supports test execution, assertions, mocking, watch mode, and code coverage, making it useful for testing React applications.

Vitest can be combined with React Testing Library to test components from the user's perspective, including their rendered output, buttons, forms, and other interactions.


1. What Is Vitest?

Vitest is a JavaScript and TypeScript testing framework designed to work especially well with Vite-based projects. It provides functions such as test(), describe(), it(), and expect() to define and verify tests.

For React applications, Vitest can test utility functions, component behavior, state changes, conditional rendering, form validation, and event handlers.

Example

import { test, expect } from 'vitest';
test('adds two numbers', () => {
  expect(2 + 3).toBe(5);
});

In this example, the test passes when the expression 2 + 3 produces the expected result of 5.

2. Why Use Vitest with React?

  • Fast execution: Designed to work efficiently with Vite.
  • Simple syntax: Provides familiar testing functions and assertions.
  • Watch mode: Can rerun relevant tests when files change.
  • React component testing: Works with React Testing Library.
  • Mocking support: Can mock functions, modules, and dependencies.
  • Code coverage: Helps identify which parts of the code are exercised by tests.
  • TypeScript support: Supports testing projects that use TypeScript.
  • Configuration flexibility: Can use Vite configuration and test-specific settings.

3. Vitest vs. React Testing Library

Feature Vitest React Testing Library
Main purpose Runs tests and evaluates assertions. Renders React components and helps interact with their output.
Common functions test(), expect(), vi.fn() render(), screen, fireEvent
Component rendering Does not provide React component rendering by itself. Provides utilities to render React components.
Mocking Provides mocking and spying APIs. Focuses on component testing utilities rather than being a test runner.
Typical use Test execution, assertions, mocks, and coverage. Test what users see and how components respond.

Vitest and React Testing Library are complementary tools. Vitest runs the tests, while React Testing Library helps render and inspect React components.

4. Installing Vitest in a React Project

First, open your React project's terminal and install Vitest and the libraries required for component testing.

npm install -D vitest jsdom
npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event

These packages provide the following functionality:

  • vitest — executes tests and provides assertions and mocking utilities.
  • jsdom — provides a simulated browser DOM environment for Node.js tests.
  • @testing-library/react — renders React components for testing.
  • @testing-library/jest-dom — provides DOM-related assertions such as toBeInTheDocument().
  • @testing-library/user-event — simulates user interactions such as clicking and typing.

For an existing Vite-based React project, Vitest can generally reuse the project's Vite setup. Ensure your installed Node.js, Vite, and Vitest versions meet the compatibility requirements of the versions you choose.

5. Configuring Vitest

In a JavaScript Vite project, create or update vite.config.js to configure Vitest for React component tests.

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig({
  plugins: [react()],
  test: {
    environment: 'jsdom',
    setupFiles: './src/test/setup.js',
    globals: true,
    css: true
  }
});

If you use a TypeScript configuration file, you can import defineConfig from vitest/config. Make sure the React plugin is installed in the project.

Understanding the configuration

  • defineConfig() — defines the project configuration.
  • plugins: [react()] — enables React support in Vite.
  • environment: 'jsdom' — provides browser-like DOM APIs for component tests.
  • setupFiles — loads setup code before test files run.
  • globals: true — makes test functions such as describe and it available globally. If omitted, import them from Vitest.
  • css: true — enables CSS processing during tests when needed.

Important: The test property is supported by Vitest's configuration. If your existing configuration uses defineConfig from vite and your editor reports a type error for the test options, import defineConfig from vitest/config instead.

6. Creating the Test Setup File

Create a file named src/test/setup.js and add the following import:

import '@testing-library/jest-dom/vitest';

This registers DOM matchers for Vitest, allowing tests to use assertions such as toBeInTheDocument(), toBeVisible(), and toBeDisabled().

7. Adding Test Scripts

Update the scripts section of your package.json:

{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "test": "vitest",
    "test:run": "vitest run",
    "test:coverage": "vitest run --coverage"
  }
}

Use npm run test to start Vitest in watch mode during development. Use npm run test:run to execute the tests once. Code coverage requires the appropriate Vitest coverage provider to be installed and configured for your version.

8. Understanding the Main Vitest Functions

Function Purpose Example
describe() Groups related tests. describe('Counter', () => {})
test() Defines a test case. test('works', () => {})
it() Alternative name for defining a test. it('works', () => {})
expect() Checks whether a value meets an expectation. expect(total).toBe(5)
vi.fn() Creates a mock function. const callback = vi.fn()
vi.spyOn() Spies on a method or function property. vi.spyOn(console, 'error')

9. Writing Your First Vitest Test

Create a utility file named src/utils.js:

export function multiply(a, b) {
  return a * b;
}

Create src/utils.test.js:

import { describe, expect, test } from 'vitest';
import { multiply } from './utils';
describe('multiply function', () => {
  test('multiplies two positive numbers', () => {
    expect(multiply(3, 4)).toBe(12);
  });
  test('returns zero when one number is zero', () => {
    expect(multiply(7, 0)).toBe(0);
  });
});

Run the tests using npm run test:run. Vitest discovers test files whose names include .test. or .spec. by default and reports whether the assertions pass.

10. Testing a React Component with Vitest

Consider a simple counter component. Create src/Counter.jsx:

import { useState } from 'react';
export default function Counter() {
  const [count, setCount] = useState(0);
  return (
    <section>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </section>
  );
}

Create src/Counter.test.jsx:

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import Counter from './Counter';
test('renders the initial count', () => {
  render(<Counter />);
  expect(screen.getByText('Count: 0')).toBeInTheDocument();
});
test('increments the count when the button is clicked', async () => {
  const user = userEvent.setup();
  render(<Counter />);
  await user.click(screen.getByRole('button', { name: 'Increment' }));
  expect(screen.getByText('Count: 1')).toBeInTheDocument();
});

The first test checks the initial output. The second simulates a user clicking the button and checks whether React updates the displayed count.

11. Testing Different React Behaviors

A. Testing conditional rendering

function Status({ isLoggedIn }) {
  return <p>{isLoggedIn ? 'Welcome back' : 'Please log in'}</p>;
}
import { render, screen } from '@testing-library/react';
import { expect, test } from 'vitest';
import Status from './Status';
test('shows the login message when logged out', () => {
  render(<Status isLoggedIn={false} />);
  expect(screen.getByText('Please log in')).toBeInTheDocument();
});

B. Testing a callback with a mock function

import { expect, test, vi } from 'vitest';
test('calls a callback', () => {
  const onSave = vi.fn();
  onSave('React');
  expect(onSave).toHaveBeenCalledOnce();
  expect(onSave).toHaveBeenCalledWith('React');
});

Mock functions are useful when verifying whether a callback was invoked and which arguments it received.

C. Testing asynchronous behavior

For UI that appears after an asynchronous operation, use asynchronous Testing Library queries such as findByRole() or findByText(). They wait for matching elements to appear within the configured timeout.

const heading = await screen.findByRole('heading', {
  name: 'Data loaded'
});
expect(heading).toBeInTheDocument();

12. Testing Forms with Vitest

Forms should be tested for input handling, submission, validation messages, and the result of user actions. The following example checks that a submitted name appears on the page.

import { useState } from 'react';
export default function NameForm() {
  const [name, setName] = useState('');
  const [submitted, setSubmitted] = useState('');
  function handleSubmit(event) {
    event.preventDefault();
    setSubmitted(name.trim());
  }
  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="name">Name</label>
      <input
        id="name"
        value={name}
        onChange={(event) => setName(event.target.value)}
      />
      <button type="submit">Submit</button>
      {submitted && <p>Submitted: {submitted}</p>}
    </form>
  );
}

Test the form by typing into the input and submitting it:

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import NameForm from './NameForm';
test('submits the entered name', async () => {
  const user = userEvent.setup();
  render(<NameForm />);
  await user.type(screen.getByRole('textbox', { name: 'Name' }), 'Asha');
  await user.click(screen.getByRole('button', { name: 'Submit' }));
  expect(screen.getByText('Submitted: Asha')).toBeInTheDocument();
});

13. Common Assertions in Vitest

Assertion Meaning
toBe(value) Checks strict equality.
toEqual(value) Checks deep equality for objects and arrays.
toBeTruthy() Checks whether a value is truthy.
toBeFalsy() Checks whether a value is falsy.
toContain(value) Checks whether a collection or string contains a value.
toHaveBeenCalled() Checks whether a mock function was called.
toHaveBeenCalledWith(...args) Checks whether a mock received specified arguments.
toBeInTheDocument() Checks whether an element is present in the document; supplied by jest-dom.
toBeVisible() Checks whether an element is visible; supplied by jest-dom.

14. Mocking Functions and Modules

Mocking replaces or observes a dependency so a test can focus on a specific behavior. Vitest provides the vi object for creating mocks, spies, and controlled return values.

import { expect, test, vi } from 'vitest';
test('uses a mock return value', () => {
  const getMessage = vi.fn().mockReturnValue('Hello React');
  expect(getMessage()).toBe('Hello React');
  expect(getMessage).toHaveBeenCalledOnce();
});

Mock network requests or complex external services when necessary, but keep tests focused on observable application behavior. Reset or restore mocks between tests when their state could affect other test cases.

15. Running Vitest Tests

  • npm run test — starts Vitest in watch mode during development.
  • npm run test:run — runs tests once and exits.
  • npx vitest path/to/file.test.jsx — runs a selected test file.
  • npx vitest --reporter=verbose — displays detailed test output.
  • npx vitest run --coverage — runs tests with coverage when the appropriate coverage provider is installed.

Watch mode is useful while developing because Vitest can rerun tests as relevant files change. A one-time run is useful for final checks and automated build pipelines.

16. Understanding Test Results

When a test passes, Vitest reports it as successful. When a test fails, it provides information about the failed assertion and often shows the expected and received values.

  • Passed: The assertion matched the expected result.
  • Failed: The actual result differed from the expectation or an error occurred.
  • Skipped: The test was intentionally excluded from the current run.
  • Test file: Groups one or more related test cases.
  • Coverage: Indicates how much of the measured code was exercised by tests; high coverage alone does not guarantee correct behavior.

17. Best Practices for Testing with Vitest

  • Test user-visible behavior rather than relying heavily on component implementation details.
  • Use accessible queries such as getByRole() and labels where possible.
  • Keep tests independent and give each test a clear purpose.
  • Use descriptive names that explain the expected behavior.
  • Prefer user-event for realistic user interactions.
  • Use asynchronous queries for elements that appear after asynchronous updates.
  • Mock network requests and external dependencies when appropriate.
  • Test normal behavior, edge cases, loading states, errors, and form validation.
  • Keep the test environment and setup files consistent across the project.
  • Run the test suite before committing changes or releasing an application.

18. Common Mistakes and Solutions

Problem Possible solution
document is not defined Configure environment: 'jsdom' for DOM-based component tests and install jsdom.
toBeInTheDocument is not a function Install jest-dom and import @testing-library/jest-dom/vitest in the setup file.
Test file is not discovered Use a filename containing .test. or .spec. and check the Vitest configuration.
Test cannot find an element Verify the accessible name and rendered content; use findBy... for elements that appear asynchronously.
Click or typing test fails Use userEvent.setup() and await interactions such as user.click() and user.type().
Tests affect one another Remove shared mutable state and reset mocks or test data between tests.
Coverage command fails Install and configure a compatible Vitest coverage provider.

19. Mini Project: Testing a React To-Do Component

Build a small To-Do component that lets users enter a task and add it to a list. Use Vitest and React Testing Library to verify the main behavior.

Example component

import { useState } from 'react';
export default function TodoList() {
  const [task, setTask] = useState('');
  const [tasks, setTasks] = useState([]);
  function addTask(event) {
    event.preventDefault();
    const value = task.trim();
    if (!value) return;
    setTasks((current) => [...current, value]);
    setTask('');
  }
  return (
    <section>
      <h2>My Tasks</h2>
      <form onSubmit={addTask}>
        <label htmlFor="task">Task</label>
        <input
          id="task"
          value={task}
          onChange={(event) => setTask(event.target.value)}
        />
        <button type="submit">Add Task</button>
      </form>
      <ul>
        {tasks.map((item, index) => (
          <li key={`${item}-${index}`}>{item}</li>
        ))}
      </ul>
    </section>
  );
}

Example test

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import TodoList from './TodoList';
test('adds a task to the list', async () => {
  const user = userEvent.setup();
  render(<TodoList />);
  await user.type(screen.getByRole('textbox', { name: 'Task' }), 'Learn Vitest');
  await user.click(screen.getByRole('button', { name: 'Add Task' }));
  expect(screen.getByText('Learn Vitest')).toBeInTheDocument();
});
test('does not add an empty task', async () => {
  const user = userEvent.setup();
  render(<TodoList />);
  await user.click(screen.getByRole('button', { name: 'Add Task' }));
  expect(screen.queryByRole('listitem')).not.toBeInTheDocument();
});

This project demonstrates testing form input, button interactions, list rendering, and empty-input behavior. Additional tests could cover duplicate tasks, clearing input, removing tasks, and handling longer task names.

20. Vitest Interview Questions and Answers

Q1. What is Vitest?

Vitest is a JavaScript and TypeScript testing framework powered by Vite. It supports test execution, assertions, mocking, watch mode, and coverage.

Q2. Why use Vitest in a React project?

It provides an efficient way to test utility functions and React component behavior, especially in projects already using Vite.

Q3. What is the purpose of React Testing Library?

It provides tools to render React components and test their output and interactions in ways that resemble how users experience the interface.

Q4. What is the difference between test() and expect()?

test() defines a test case. expect() creates an assertion that checks whether a value or behavior meets an expected condition.

Q5. What is jsdom?

jsdom simulates browser-like DOM APIs in a Node.js environment, allowing many component tests to run without opening a real browser.

Q6. What is mocking?

Mocking substitutes or observes a function or dependency so tests can verify behavior without relying on the real implementation.

Q7. What is watch mode?

Watch mode keeps Vitest running during development and reruns relevant tests when files change.

Q8. What is the purpose of vi.fn()?

vi.fn() creates a mock function that can record calls and return controlled values.

Q9. What is the difference between getBy, queryBy, and findBy?

getBy returns a matching element immediately or throws if none is found. queryBy returns null when there is no match, making it useful for absence checks. findBy returns a promise and waits for an element to appear.

Q10. Does passing all tests guarantee that an application has no bugs?

No. Tests can only verify the scenarios and conditions they cover. Good testing combines unit tests, component tests, integration tests, and appropriate manual or end-to-end testing.

21. Practice Exercises

  1. Write a Vitest test for a function that subtracts two numbers.
  2. Test a React button that changes its label after being clicked.
  3. Test a login form's required-field validation message.
  4. Mock a function and verify that it is called with the correct arguments.
  5. Test a component that displays a loading message before showing data.
  6. Test an error message when a mocked request fails.
  7. Create a To-Do component and test adding and rejecting empty tasks.

22. Revision Checklist

  • Understand the purpose of Vitest.
  • Install Vitest, jsdom, React Testing Library, jest-dom, and user-event.
  • Configure the DOM environment and test setup file.
  • Write tests using describe(), test(), and expect().
  • Test React components and user interactions.
  • Use mock functions and asynchronous queries correctly.
  • Run tests in watch mode and one-time mode.
  • Read failure messages and fix failing assertions.
  • Practice testing forms, lists, loading states, and error states.

23. Official Learning Resources

24. Learn React JS with JustAcademy

Strengthen your React skills by learning components, props, state, hooks, event handling, application development, and testing techniques.

JustAcademy React JS Training Course

Explore the course and learn how to build and test React applications through practical exercises.

Register for React JS Course Demo

Conclusion

Vitest provides a fast and flexible testing framework for React projects, particularly those built with Vite. When combined with React Testing Library, it helps developers verify rendered output, state updates, form behavior, user interactions, asynchronous UI, and error handling. Practicing these techniques makes React applications easier to maintain and more reliable.

Previous Next
whatsapp