Hackforge Academy

Category: java

how to write unit-test in react

Published on 30 Mar 2026

Explanation

Test whether a React component renders without crashing using React Testing Library render method.

Code:

import { render } from '@testing-library/react';
import App from './App';

test('renders App component without crashing',
 () => {
  render(<App />);
});

Explanation

Test whether specific text is displayed in the component using screen.getByText().

Code:

import { render, screen } from 
'@testing-library/react';

import App from './App';

test('renders welcome message', () => {
  render(<App />);
  const textElement = screen.getByText('
Welcome to React
');
  expect(textElement).toBeInTheDocument();
});

Explanation

Test button click events using fireEvent to simulate user interaction.

Code:

import { render, screen, fireEvent } from 
'@testing-library/react';
import Counter from './Counter';

test('increments counter on button click',()
=> {
  render(<Counter />);
  const button = screen.getByText('Incrmt');
  fireEvent.click(button);
  expect(screen.getByText('Count: 1')).
  toBeInTheDocument();
});

Explanation

Test input field value change using fireEvent.change().

Code:

import { render, screen, fireEvent } from 
'@testing-library/react';
import InputBox from './InputBox';

test('updates input value on change', () => 
{
  render(<InputBox />);
  const input = screen.getByRole('textbox');
  fireEvent.change(input, { target: 
{ value: 'React Test' } });
  expect(input.value).toBe('React Test');
});

Explanation

Test conditional rendering by checking whether an element appears after clicking a toggle button.

Code:

import { render, screen, fireEvent } from 
'@testing-library/react';
import Toggle from './Toggle';

test('shows message after button click', 
() => {
  render(<Toggle />);
  const button = screen.getByText('Show');
  fireEvent.click(button);
  expect(screen.getByText('Hello User'))
.toBeInTheDocument();
});

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community