MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Writing Unit Tests for Functional Components0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
13.1Modern React Testing Stack (Vitest & Testing Library)13.2Writing Unit Tests for Functional Components13.3Simulating User Events and Testing Asynchronous Updates
HomeTutorialsReact.js for IntermediateWriting Unit Tests for Functional Components
Simulating User Events and Testing Asynchronous Updates

Writing Unit Tests for Functional Components

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. Anatomy of a Component Unit Test

A standard unit test in React follows the AAA Pattern:

  1. 1
    Arrange: Render the component using render(<MyComponent />) and prepare props or mocks.
  2. 2
    Act: Simulate user interactions (typing, clicking, toggling) using @testing-library/user-event.
  3. 3
    Assert: Verify that the expected DOM elements, text, or callbacks responded correctly.
1[Arrange: render(<Counter />)] ──► [Act: user.click(button)] ──► [Assert: expect(text).toHaveTextContent('1')]

2. Complete Example: Testing a Course Card Component

Let's write a comprehensive test suite for an interactive course card:

1// src/components/CourseCard.jsx
2import React from 'react';
3 
4export default function CourseCard({ course, onEnroll }) {
5 return (
6 <div className="course-card">
7 <h3 data-testid="course-title">{course.title}</h3>
8 <p>{course.description}</p>
9 <span className="price">${course.price}</span>
10
11 <button
12 type="button"
13 disabled={course.isSoldOut}
14 onClick={() => onEnroll(course.id)}
15 >
16 {course.isSoldOut ? 'Sold Out' : 'Enroll Now'}
17 </button>
18 </div>
19 );
20}

The Vitest Test File:

1// src/components/__tests__/CourseCard.test.jsx
2import { describe, it, expect, vi } from 'vitest';
3import { render, screen } from '@testing-library/react';
4import userEvent from '@testing-library/user-event';
5import CourseCard from '../CourseCard';
6 
7describe('CourseCard Component', () => {
8 const mockCourse = {
9 id: 'c-101',
10 title: 'React.js Mastery',
11 description: 'Master modern frontend web engineering.',
12 price: 99,
13 isSoldOut: false
14 };
15 
16 it('renders course information correctly', () => {
17 render(<CourseCard course={mockCourse} onEnroll={vi.fn()} />);
18 
19 // Assert title and price are in the document
20 expect(screen.getByRole('heading', { level: 3 })).toHaveTextContent('React.js Mastery');
21 expect(screen.getByText(/Master modern frontend/i)).toBeInTheDocument();
22 expect(screen.getByText('$99')).toBeInTheDocument();
23 });
24 
25 it('invokes onEnroll callback with course ID when Enroll button is clicked', async () => {
26 // vi.fn() creates a mock spy function in Vitest
27 const handleEnroll = vi.fn();
28 const user = userEvent.setup();
29 
30 render(<CourseCard course={mockCourse} onEnroll={handleEnroll} />);
31 
32 const enrollButton = screen.getByRole('button', { name: /enroll now/i });
33 await user.click(enrollButton);
34 
35 // Verify spy function was called exactly once with 'c-101'
36 expect(handleEnroll).toHaveBeenCalledTimes(1);
37 expect(handleEnroll).toHaveBeenCalledWith('c-101');
38 });
39 
40 it('disables the button when the course is sold out', () => {
41 const soldOutCourse = { ...mockCourse, isSoldOut: true };
42 render(<CourseCard course={soldOutCourse} onEnroll={vi.fn()} />);
43 
44 const button = screen.getByRole('button', { name: /sold out/i });
45 expect(button).toBeDisabled();
46 });
47});

3. Why userEvent Over fireEvent

Notice line 27: const user = userEvent.setup(); await user.click(button);.

  • fireEvent.click(): Dispatches a synthetic DOM event instantly without simulating hover, focus, or active state sequences.
  • userEvent.click(): Faithfully simulates what a real human does: moves cursor, fires mouseover, hovers, focuses the element, clicks, and fires blur upon leaving.

Always prefer @testing-library/user-event for interaction testing!


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the recommended tool for simulating user clicks and keystrokes in React Testing Library?
Question 2
What Vitest function creates a mock spy function to verify if a callback prop was invoked?
Question 3
What matcher from @testing-library/jest-dom asserts that a button has its HTML disabled attribute active?
Question 4
Why must calls to userEvent methods (like await user.click(...) or await user.type(...)) be awaited?
Question 5
In the AAA testing pattern, what does the "Act" phase represent?
Next Lesson

Simulating User Events and Testing Asynchronous Updates

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Modern React Testing Stack (Vitest & Testing Library)Simulating User Events and Testing Asynchronous Updates

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext