React Testing Library with Vitest - Complete Learning Path (RTL + Vitest + API Mocking + GraphQL + Apollo Client + MSW + TDD + Focus Flow Fundamentals & Testing Tutorials)
A comprehensive collection of progressive React Testing Library tutorials designed to take you from beginner to advanced. This repository contains five complete projects that build upon each other, teaching you everything from basic setup to advanced testing patterns including GraphQL API mocking and complex integration testing.
- Repository Overview
- Learning Path
- Project Structure
- Technology Stack
- Prerequisites
- Getting Started
- Project Descriptions
- Environment Variables
- Testing Setup Across Projects
- Running Projects
- Key Learning Outcomes
- Resources
- Contributing
- Keywords
- Conclusion
This repository is a complete learning resource for React Testing Library with Vitest. It contains five progressive projects that teach you:
- ✅ Project 1 - Basic setup and boilerplate configuration
- ✅ Project 2 - Fundamental testing concepts and query methods
- ✅ Project 3 - Test-Driven Development (TDD) workflow
- ✅ Project 4 - API mocking with Mock Service Worker (MSW)
- ✅ Project 5 - Advanced GraphQL testing with Apollo Client and MSW
Each project is self-contained with its own dependencies, configuration, and comprehensive documentation. You can follow them sequentially for a complete learning experience or jump to specific topics of interest.
-
Start Here:
01-React-Testing-Library-Vitest-Boilerplate- Learn basic setup and configuration
- Understand the testing environment
- Write your first tests
-
Fundamentals:
02-React-Testing-Library-Fundamental-Tutorials- Master query methods (text, role, label)
- Learn user interaction testing
- Understand form testing patterns
-
TDD Practice:
03-Focus-Flow-Test-Driven-Development-Testing-Tutorial- Practice Test-Driven Development
- Build a complete application with TDD
- Learn Context API testing
-
API Mocking:
04-Mock-Service-Worker-Testing-Tutorial- Mock REST APIs with MSW
- Test components with API calls
- Handle async operations in tests
-
Advanced Topics:
05-GitHub-Users-Search-Application-Testing-Tutorial- Mock GraphQL APIs
- Test Apollo Client integration
- Test data visualization components
By completing all projects, you will:
- Understand React Testing Library philosophy and best practices
- Master all query methods (getBy, queryBy, findBy, getAllBy, etc.)
- Write comprehensive unit and integration tests
- Practice Test-Driven Development (TDD)
- Mock REST and GraphQL APIs with MSW
- Test components with Context API
- Test async operations and error scenarios
- Write maintainable, accessible, and reliable tests
react-testing-library-tutorials/
├── 01-React-Testing-Library-Vitest-Boilerplate/
│ ├── src/
│ │ ├── __tests__/ # Basic component tests
│ │ ├── App.tsx # Main app component
│ │ ├── Random.tsx # Example component
│ │ └── vitest.setup.ts # Vitest configuration
│ ├── package.json
│ ├── vite.config.ts
│ └── README.md # Complete documentation
│
├── 02-React-Testing-Library-Fundamental-Tutorials/
│ ├── src/
│ │ ├── __tests__/ # Component tests
│ │ ├── 01-search-by-text/ # Tutorial 1: Text queries
│ │ ├── 02-tdd-example/ # Tutorial 2: TDD basics
│ │ ├── 03-search-by-role/ # Tutorial 3: Role queries
│ │ ├── 04-user-interactions/# Tutorial 4: User events
│ │ ├── 05-form-testing/ # Tutorial 5: Form tests
│ │ └── 06-reviews-app/ # Tutorial 6: Integration
│ ├── package.json
│ ├── vite.config.ts
│ └── README.md # Complete documentation
│
├── 03-Focus-Flow-Test-Driven-Development-Testing-Tutorial/
│ ├── src/
│ │ ├── __tests__/ # TDD tests
│ │ ├── components/ # Task management components
│ │ ├── FlowContext.tsx # Context API implementation
│ │ └── utils.ts # Custom hooks
│ ├── package.json
│ ├── vite.config.ts
│ └── README.md # Complete documentation
│
├── 04-Mock-Service-Worker-Testing-Tutorial/
│ ├── src/
│ │ ├── __tests__/ # Tests with MSW
│ │ ├── components/ # Posts management components
│ │ ├── hooks/
│ │ │ └── usePosts.ts # API hook with Axios
│ │ └── mocks/ # MSW handlers
│ │ ├── handlers.ts # REST API handlers
│ │ └── server.ts # MSW server setup
│ ├── public/
│ │ └── mockServiceWorker.js # MSW service worker
│ ├── db.json # json-server database
│ ├── package.json
│ ├── vite.config.ts
│ └── README.md # Complete documentation
│
├── 05-GitHub-Users-Search-Application-Testing-Tutorial/
│ ├── src/
│ │ ├── __tests__/ # GraphQL tests
│ │ ├── components/
│ │ │ ├── charts/ # Chart components (Recharts)
│ │ │ ├── form/ # Search form
│ │ │ ├── ui/ # shadcn/ui components
│ │ │ └── user/ # User profile components
│ │ ├── apolloClient.ts # Apollo Client setup
│ │ ├── queries.ts # GraphQL queries
│ │ ├── mocks/ # MSW GraphQL handlers
│ │ └── utils.ts # Data processing utilities
│ ├── .env.local # GitHub token (see setup)
│ ├── components.json # shadcn/ui config
│ ├── package.json
│ ├── vite.config.ts
│ └── README.md # Complete documentation
│
├── .gitignore # Git ignore file
└── README.md # This file- React 18.3.1 - Modern React library for building user interfaces
- TypeScript 5.5.3+ - Type-safe JavaScript with enhanced developer experience
- Vite 5.4.8+ - Next-generation frontend build tool for fast development
- Vitest 2.1.3+ - Fast unit test framework powered by Vite
- React Testing Library 16.0.1+ - Simple and complete React DOM testing utilities
- @testing-library/jest-dom 6.5.0+ - Custom Jest matchers for DOM elements
- @testing-library/user-event 14.5.2+ - Simulate user interactions in tests
- jsdom 25.0.1+ - JavaScript implementation of the DOM for testing
- react-icons 5.3.0 - Icon library
- validator 13.12.0 - Form validation library
- lucide-react 0.461.0 - Icon library
- MSW 2.6.6 - Mock Service Worker for API mocking
- Axios 1.7.8 - HTTP client for API calls
- json-server 1.0.0-beta.3 - Mock REST API server (optional)
- Apollo Client 3.11.10 - GraphQL client for React
- GraphQL 16.9.0 - Query language for APIs
- MSW 2.6.8 - Mock Service Worker for GraphQL mocking
- Recharts 2.13.3 - Charting library for React
- Radix UI - Unstyled, accessible UI components
@radix-ui/react-label@radix-ui/react-slot@radix-ui/react-toast
- shadcn/ui - High-quality React components
- lucide-react 0.456.0 - Icon library
- Tailwind CSS 3.4.14 - Utility-first CSS framework
- ESLint 9.11.1+ - Code linting and quality assurance
- Tailwind CSS 3.4.14 - Utility-first CSS framework (Projects 1-4)
- PostCSS 8.4.47+ - CSS transformation tool
Before you begin, ensure you have the following installed on your system:
- Node.js (version 18.x or higher recommended)
- npm (comes with Node.js) or yarn or pnpm
- Git (for cloning the repository)
- A code editor (VS Code recommended)
- Basic knowledge of React and JavaScript/TypeScript
- Understanding of HTML and CSS
- Familiarity with terminal/command line
- Basic understanding of testing concepts (helpful but not required)
- GitHub Personal Access Token - Required for accessing GitHub GraphQL API
- Instructions: Go to GitHub Settings → Developer settings → Personal access tokens
- Required scopes:
read:userandpublic_repo
node --version # Should show v18.x or higher
npm --version # Should show 9.x or higher
git --version # Any recent versiongit clone <repository-url>
cd react-testing-library-tutorialsEach project is independent and has its own dependencies. Navigate to any project directory:
cd 01-React-Testing-Library-Vitest-BoilerplateEach project needs its dependencies installed separately:
npm installSee the Running Projects section for details.
npm testFor detailed instructions on each project, see their individual README files.
Location: 01-React-Testing-Library-Vitest-Boilerplate/
Learning Objectives:
- Set up Vitest and React Testing Library
- Configure TypeScript for testing
- Write basic component tests
- Understand test file structure
- Learn Jest-DOM matchers
Key Features:
- Minimal React application setup
- Pre-configured testing environment
- Example test files
- TypeScript configuration for testing
- Basic testing patterns
Technologies Used:
- React, TypeScript, Vite
- Vitest, React Testing Library
- Tailwind CSS
Read More: See 01-React-Testing-Library-Vitest-Boilerplate/README.md
Location: 02-React-Testing-Library-Fundamental-Tutorials/
Learning Objectives:
- Master all query methods (getBy, queryBy, findBy, getAllBy)
- Learn text-based and role-based queries
- Understand user interaction testing
- Practice form validation testing
- Build integration tests
Key Features:
- Six progressive sandbox tutorials:
- Search by Text - Text query methods
- TDD Example - Test-Driven Development basics
- Search by Role - Role-based queries
- User Interactions - fireEvent vs userEvent
- Form Testing - Form validation patterns
- Reviews App - Complete integration testing
Technologies Used:
- React, TypeScript, Vite
- Vitest, React Testing Library
- react-icons, validator
- Tailwind CSS
Read More: See 02-React-Testing-Library-Fundamental-Tutorials/README.md
Location: 03-Focus-Flow-Test-Driven-Development-Testing-Tutorial/
Learning Objectives:
- Practice Test-Driven Development (TDD)
- Write tests before implementation
- Understand Red-Green-Refactor cycle
- Test React Context API
- Test custom hooks
- Build integration tests
Key Features:
- Task management application
- Two implementation patterns (custom hook and Context)
- Comprehensive test coverage
- TDD workflow demonstration
- Component integration testing
Technologies Used:
- React, TypeScript, Vite
- Vitest, React Testing Library
- lucide-react
- Tailwind CSS
Read More: See 03-Focus-Flow-Test-Driven-Development-Testing-Tutorial/README.md
Location: 04-Mock-Service-Worker-Testing-Tutorial/
Learning Objectives:
- Set up Mock Service Worker (MSW)
- Mock REST API calls in tests
- Mock API calls in development
- Test components with API integration
- Handle async operations in tests
- Test error scenarios
Key Features:
- Posts management application
- MSW setup for browser and Node.js
- REST API mocking with MSW
- CRUD operations testing
- Error handling tests
- Real API simulation
Technologies Used:
- React, TypeScript, Vite
- Vitest, React Testing Library
- MSW, Axios
- json-server (optional)
- Tailwind CSS
Read More: See 04-Mock-Service-Worker-Testing-Tutorial/README.md
Location: 05-GitHub-Users-Search-Application-Testing-Tutorial/
Learning Objectives:
- Integrate Apollo Client with React
- Query GitHub GraphQL API
- Mock GraphQL queries with MSW
- Test GraphQL-based components
- Test data visualization components
- Mock chart components in tests
Key Features:
- GitHub user search application
- GraphQL API integration
- Data visualization with Recharts
- shadcn/ui components
- Comprehensive testing with MSW
- Error handling and loading states
Technologies Used:
- React, TypeScript, Vite
- Vitest, React Testing Library
- Apollo Client, GraphQL
- MSW (GraphQL mocking)
- Recharts
- Radix UI (shadcn/ui)
- Tailwind CSS
Special Requirements:
- GitHub Personal Access Token (see Environment Variables section)
Read More: See 05-GitHub-Users-Search-Application-Testing-Tutorial/README.md
This project requires a GitHub Personal Access Token to access the GitHub GraphQL API.
-
Create a GitHub Personal Access Token:
- Go to GitHub Settings → Developer settings → Personal access tokens → Tokens (classic)
- Click "Generate new token (classic)"
- Give it a name (e.g., "GitHub Search App")
- Select scopes:
read:userandpublic_repo - Click "Generate token"
- Copy the token (you won't see it again!)
-
Create
.env.localfile:cd 05-GitHub-Users-Search-Application-Testing-Tutorial touch .env.local -
Add your token:
VITE_GITHUB_TOKEN=your_github_token_here
Important Notes:
- Replace
your_github_token_herewith your actual GitHub token - Never commit
.env.localto version control (it's already in.gitignore) - The
VITE_prefix is required for Vite to expose the variable
- Replace
-
For Testing:
MSW mocks handle GraphQL queries in tests, so you don't need a real token for testing. However, if you want to test against the real API, you can use a token in tests.
Projects 1-4 do not require environment variables.
All projects share similar testing setup patterns:
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
globals: true, // Enable global test APIs
environment: "jsdom", // Use jsdom for DOM APIs
setupFiles: "./src/vitest.setup.ts", // Global test setup
},
});import { expect, afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
import * as matchers from "@testing-library/jest-dom/matchers";
expect.extend(matchers);
afterEach(() => {
cleanup();
});Projects 4 and 5 include MSW setup:
import server from "./mocks/server";
beforeAll(() => {
server.listen();
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
});All projects use the same test command:
npm test # Watch mode (default)
npm test -- --run # Run once (CI mode)
npm test -- --ui # UI mode
npm test -- --coverage # With coverageAll projects use the same command to start the development server:
npm run devThe application will be available at http://localhost:5173 (or the next available port).
npm run buildnpm run previewnpm run lintOptional json-server for manual API testing:
npm run serverThis starts a mock REST API server at http://localhost:4000.
You will be able to:
✅ Setup and Configure Testing Environment
- Set up Vitest and React Testing Library
- Configure TypeScript for testing
- Set up MSW for API mocking
✅ Master Query Methods
- Use
getBy,queryBy,findByvariants - Use
getAllByfor multiple elements - Choose appropriate queries based on use case
✅ Test User Interactions
- Simulate user events with
userEvent - Test form submissions and validations
- Handle async user interactions
✅ Practice Test-Driven Development
- Write tests before implementation
- Follow Red-Green-Refactor cycle
- Build confidence with TDD
✅ Mock APIs
- Mock REST APIs with MSW
- Mock GraphQL queries with MSW
- Test error scenarios
- Handle async operations
✅ Test Complex Applications
- Test Context API
- Test custom hooks
- Test data visualization components
- Write integration tests
✅ Follow Best Practices
- Write accessible tests
- Test user behavior, not implementation
- Keep tests maintainable
- Write fast and reliable tests
- React Testing Library - Official RTL documentation
- Vitest - Vitest documentation
- MSW - Mock Service Worker documentation
- Apollo Client - Apollo Client documentation
- GraphQL - GraphQL documentation
- Common Mistakes with React Testing Library - Kent C. Dodds
- Testing JavaScript - Testing course by Kent C. Dodds
- React Testing Library Tutorial - Robin Wieruch
- TDD Best Practices - FreeCodeCamp
- React Testing Library Crash Course - YouTube
- MSW Tutorial - YouTube
- Apollo Client Tutorial - YouTube
- React Testing Library GitHub - GitHub repository
- Vitest GitHub - GitHub repository
- MSW GitHub - GitHub repository
This is an educational repository. Contributions, improvements, and suggestions are welcome!
- Report Issues - Found a bug or have a suggestion? Open an issue
- Improve Documentation - Help make the documentation clearer
- Add Examples - Share additional testing patterns
- Fix Bugs - Submit pull requests for bug fixes
- Follow the existing code style
- Add tests for new features
- Update documentation as needed
- Keep commits clear and focused
- React Testing Library (RTL) - Testing utilities for React
- Vitest - Modern test runner built on Vite
- Jest-DOM - Custom matchers for DOM assertions
- jsdom - DOM implementation for Node.js
- Test-Driven Development (TDD) - Development approach writing tests first
- Unit Testing - Testing individual components
- Integration Testing - Testing component interactions
- Mocking - Simulating dependencies in tests
- getBy* - Find element, throws if not found
- queryBy* - Find element, returns null if not found
- findBy* - Find element asynchronously
- getAllBy* - Find all elements, throws if none found
- queryAllBy* - Find all elements, returns empty array if none found
- findAllBy* - Find all elements asynchronously
- userEvent - Simulate user interactions (preferred)
- fireEvent - Simulate DOM events (legacy)
- click - Simulate click events
- type - Simulate typing
- clear - Clear input field
- Mock Service Worker (MSW) - API mocking library
- Service Worker - Browser API for intercepting requests
- Request Handler - Function defining mock responses
- GraphQL Mocking - Mocking GraphQL queries
- REST API Mocking - Mocking REST endpoints
- Component - Reusable UI building blocks
- Props - Data passed to components
- State - Component internal data
- Context API - React's built-in state management
- Custom Hooks - Reusable stateful logic
- useQuery - Apollo Client hook for GraphQL queries
- GraphQL - Query language for APIs
- Apollo Client - GraphQL client for React
- Query - GraphQL operation for fetching data
- Variables - Parameters passed to queries
- Schema - GraphQL API structure
This repository provides a complete learning path for mastering React Testing Library. By following the projects in sequence, you'll progress from basic setup to advanced testing patterns, building real-world applications along the way.
- Start Simple - Learn basic setup with Project 1
- Master Fundamentals - Build testing skills with Project 2
- Practice TDD - Develop TDD habits with Project 3
- Mock APIs - Learn API mocking with Project 4
- Advanced Testing - Master complex scenarios with Project 5
- ✅ Simple React components with tests
- ✅ Complete form validation systems
- ✅ Task management applications
- ✅ Posts management with API integration
- ✅ GitHub user search with GraphQL and data visualization
- Start with Project 1 - Set up your testing environment
- Follow the sequence - Complete projects in order
- Practice regularly - Testing is a skill that improves with practice
- Build your own projects - Apply what you've learned
- Share your work - Help others learn by sharing
- Read the documentation - Each project has comprehensive README files
- Write code along - Don't just read, write the code yourself
- Experiment - Try modifying examples and see what happens
- Test your own code - Apply patterns to your own projects
- Join communities - Engage with the testing community
- Stay updated - Testing libraries evolve, stay current
Remember: The goal is not just to write tests, but to write good tests that help you build better applications with confidence.
Feel free to use this project repository and extend this project further!
If you have any questions or want to share your work, reach out via GitHub or my portfolio at https://arnob-mahmud.vercel.app/.
Enjoy building and learning! 🚀
Thank you! 😊