Hello! Welcome to the first lesson of our final module, Testing, Building, and Deploying.
In the previous module, we reached the peak of component architecture, learning to craft highly dynamic, flexible, and type-safe components using advanced TypeScript patterns. Now, we shift our focus from building to ensuring quality. Writing robust software isn't just about elegant code; it's about creating applications that are reliable, maintainable, and behave as expected. Testing is the cornerstone of that discipline.
Today, your goal is to set up a testing environment with Vitest and React Testing Library. We'll lay the foundation for the entire module by configuring a modern, fast, and efficient testing suite for our Vite-powered React and TypeScript application.
1. Why Vitest? The Modern Choice for Vite Projects
Before we install anything, it's important to understand why we're choosing our tools. In the world of JavaScript testing, Jest has long been the dominant framework. However, the ecosystem has evolved. With the rise of modern build tools like Vite that use native ES Modules (ESM), Jest's architecture, which was built for the older CommonJS module system, can lead to complex configuration and slower performance.
Vitest was created to solve this. It's a test runner built by the same team as Vite, designed to integrate seamlessly with a Vite-based development environment.
Why I Chose Vitest Over Jest: 10x Faster Tests & Native ESM Support
This article, "Why I Chose Vitest Over Jest", perfectly captures the rationale for our choice. It details the common pain points of using Jest in a modern Vite project and highlights the significant advantages of Vitest.
Please read the following parts of the article to understand the context: Start with the introduction to grasp the author's core argument. Read the section "The Problem" and "The Challenge" to see the common issues with Jest in a Vite stack (slow startup, ESM issues, config complexity). Skim the "Evaluation Criteria" to see what makes a good testing framework. Read the "Deep Dive: Vitest" section to understand how Vitest's architecture leverages your existing Vite config. Finally, read the section "The Decision", focusing on Reason 1 (Vite Integration) and Reason 2 (Performance). Focus on the why—the strategic reasons for choosing Vitest over the incumbent.
As you've read, the key benefits of Vitest are:
- Speed: It's significantly faster due to its use of Vite's native ESM support and
esbuildfor transformations. - Seamless Integration: It reuses your
vite.config.ts, meaning your tests run in an environment that is nearly identical to your development and production builds. Path aliases, plugins, and CSS handling work out of the box. - Modern API: It offers a Jest-compatible API, making it familiar to many, but with modern features like a built-in UI and Hot Module Replacement (HMR) for tests.

2. The Testing Toolkit: Our Core Dependencies
To get our environment running, we need a few key packages that work together:
vitest: The test runner. It finds your test files, executes the test code, and reports the results (pass or fail).jsdom: A JavaScript implementation of a browser environment. Since our tests run in Node.js (which has no DOM),jsdomcreates a simulated DOM so our React components can be rendered and inspected.@testing-library/react: A library providing simple utilities to render components and interact with them. Its philosophy is to test components in a way that resembles how a user would interact with them, leading to more robust tests.@testing-library/jest-dom: An essential companion library that adds custom DOM-specific matchers to Vitest'sexpectfunction. This lets you write more readable assertions likeexpect(element).toBeInTheDocument()instead of more verbose checks.@testing-library/user-event: A library for simulating user interactions like typing, clicking, and hovering in a way that's more realistic than firing raw DOM events. We'll use this extensively in later lessons.
3. Step-by-Step Environment Setup
Now, let's get our hands dirty and set up the environment. The following video is a comprehensive guide that walks through the entire process, from installing dependencies to writing the first test. We will follow it step-by-step.
Setting up vite, React, TypeScript, eslint, prettier, vitest, testing-library and react-router
This video from Coding Garden provides a clear, practical walkthrough of setting up a complete testing environment for a Vite, React, and TypeScript project. We will focus on the Vitest and Testing Library portions.
Follow along with the video to install and configure the core testing packages. Install Dependencies (23:47 - 25:05 & 27:11 - 28:50): The video breaks this into two parts. First, install vitest. Then, after some config, it installs @testing-library/react and @testing-library/jest-dom. You can do this in one go with the command I'll provide below. Configure Vitest (25:05 - 27:11): Watch how the vite.config.ts file is modified to include the test configuration block. Pay attention to the environment and setupFiles properties. Create Setup File (28:50 - 29:59): See how the setupTests.ts file is created and how it's used to extend Vitest's expect with the matchers from jest-dom.
Let's consolidate those steps.
Step 3.1: Install All Dependencies
Open your project's terminal and run the following command to install everything we need as development dependencies:
npm install -D vitest jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event
Step 3.2: Configure vite.config.ts
Modify your vite.config.ts file to include a test property. You'll also need to add a "triple-slash directive" at the top to reference Vitest's types.
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
test: {
globals: true, // Optional: gives jest-like global access to describe, test, expect
environment: 'jsdom',
setupFiles: './src/setupTests.ts', // Path to your setup file
},
})
globals: true: This makes functions likedescribe,it, andexpectavailable in all test files without needing to import them. It mimics the behavior of Jest and is convenient, though explicit imports are also a valid (and sometimes preferred) style.environment: 'jsdom': This tells Vitest to set up the JSDOM environment for our tests.setupFiles: This points to a file that will be executed before each test file runs. It's the perfect place for global setup.
Step 3.3: Create setupTests.ts
In your src/ directory, create a new file named setupTests.ts. This file will import the jest-dom matchers, making them available to all your tests. It's also best practice to add a cleanup function that runs after each test.
// src/setupTests.ts
import '@testing-library/jest-dom';
import { cleanup } from '@testing-library/react';
import { afterEach } from 'vitest';
// Ensures that the JSDOM is cleaned up after each test.
afterEach(() => {
cleanup();
});
Step 3.4: Update tsconfig.json
To ensure TypeScript understands the global test functions (if you set globals: true) and the new matchers from @testing-library/jest-dom, update your tsconfig.json:
{
"compilerOptions": {
// ... other options
"types": ["vitest/globals", "@testing-library/jest-dom"]
},
// ... other properties
}
Step 3.5: Add package.json Scripts
Finally, let's add some scripts to package.json to make running tests easy.
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"test": "vitest",
"test:ui": "vitest --ui"
},
npm test: Runs Vitest in "watch mode." It will run all tests and then wait for file changes to re-run only the affected tests.npm run test:ui: Starts Vitest's UI, a powerful browser-based interface for running, viewing, and debugging your tests.
4. Writing Your First Test (A "Smoke Test")
With the setup complete, let's write a simple "smoke test" to ensure everything is working correctly. This test will render your App component and check if it displays something.
Setting up vite, React, TypeScript, eslint, prettier, vitest, testing-library and react-router
Let's return to the Coding Garden video to see how to write and run our first basic test.
Watch from 29:59 to 34:25. This part covers: Creating a test file (e.g., App.test.tsx) next to the component it's testing. The basic structure: describe to group tests, and it for an individual test case. Using render from React Testing Library to render the component. Using screen to query the rendered output. Using expect to make an assertion. Running the test via the command line.
Create a file named App.test.tsx inside your src/ directory, next to App.tsx.
// src/App.test.tsx
import { render, screen } from '@testing-library/react';
import App from './App';
describe('App component', () => {
it('renders the Vite and React logos', () => {
// 1. Arrange: Render the component
render(<App />);
// 2. Act: (No user action needed for this test)
// 3. Assert: Check that the expected content is on the screen
const reactLogo = screen.getByAltText('React logo');
const viteLogo = screen.getByAltText('Vite logo');
expect(reactLogo).toBeInTheDocument();
expect(viteLogo).toBeInTheDocument();
});
it('renders the main heading', () => {
render(<App />);
const heading = screen.getByRole('heading', {
level: 1, // Corresponds to <h1>
});
expect(heading).toHaveTextContent('Vite + React');
});
});
Now, run npm test in your terminal. Vitest should find your new test file and execute it. You should see a passing result!
.0cf30970_2gf3Hp.gif)
Test your understanding!
Why is using screen.getByRole('heading', { level: 1 }) generally preferred over screen.getByText('Vite + React') for finding the <h1> element?
Show answer
Using getByRole tests the component from an accessibility perspective. It verifies not just that the text is present, but that it's correctly marked up as a top-level heading (<h1>), which is important for screen reader users and search engines. Querying by role is more resilient to changes in the text content and more aligned with testing from a user's perspective, which is the core philosophy of React Testing Library.
Conclusion
Congratulations! You have successfully set up a professional-grade testing environment. This setup is fast, modern, and tightly integrated with your development workflow.
Key Takeaways:
- Vitest is the ideal test runner for Vite projects due to its performance and seamless configuration reuse.
- A complete testing stack includes a test runner (
vitest), a simulated DOM (jsdom), a component testing utility (@testing-library/react), and custom matchers (@testing-library/jest-dom). - Configuration is straightforward: you modify
vite.config.ts, create a globalsetupTests.ts, and updatetsconfig.json. - Tests are structured with
describeblocks for grouping anditblocks for individual test cases, following an "Arrange-Act-Assert" pattern.
Preview of the Next Lesson:
Now that our testing infrastructure is in place, we can start writing meaningful tests. In the next lesson, "Write unit tests for presentational components and assert their output," we will dive deep into the practice of testing, learning how to effectively test the UI of our components using the tools we've just configured.