React js

Unit Testing In React

What is Unit Testing?

  • Unit testing means testing individual pieces of your code (functions, components) to ensure they work as expected.

  • Helps catch bugs early, improves code quality, and makes refactoring safer.


Popular JavaScript Testing Tools

Tool Purpose
Jest Testing framework by Facebook, great for React
React Testing Library Focuses on testing React components the way users interact with them
Mocha / Chai General JS testing frameworks/assertion libraries

Example: Testing a Simple Function with Jest

js
// sum.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
js
// sum.test.js
const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});

Run tests with:

bash
npx jest

Testing a React Component with React Testing Library

jsx
// Button.js
import React from 'react';

function Button({ onClick, children }) {
return <button onClick={onClick}>{children}</button>;
}

export default Button;

jsx
// Button.test.js
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';

test('calls onClick when clicked', () => {
const handleClick = jest.fn();
render(<Button onClick={handleClick}>Click me</Button>);

fireEvent.click(screen.getByText(/click me/i));
expect(handleClick).toHaveBeenCalledTimes(1);
});


Benefits of Unit Testing

  • Catch errors early.

  • Prevent regressions when changing code.

  • Document expected behavior.

  • Boost confidence in code.


Summary

  • Unit tests focus on small, isolated pieces of code.

  • Jest is a popular testing framework for JavaScript.

  • React Testing Library lets you test React components from a user perspective.

  • Write tests for functions and UI interactions.

Leave a Reply

Your email address will not be published. Required fields are marked *