Unit Testing React Components with Jest

imyusufakhtar

Md Yusuf

Posted on September 30, 2024

Unit Testing React Components with Jest

Unit testing in React with Jest is a powerful way to ensure your components work as expected. Here’s a quick guide on how to get started:

1. Setup

Make sure you have Jest installed. If you created your React app using Create React App, Jest is already included. Otherwise, you can install it using:

npm install --save-dev jest
Enter fullscreen mode Exit fullscreen mode

2. Writing Tests

Create a test file alongside your component file (e.g., MyComponent.test.js).

Example Component (MyComponent.js)

import React from 'react';

const MyComponent = ({ title }) => {
    return <h1>{title}</h1>;
};

export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

Example Test (MyComponent.test.js)

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

test('renders title', () => {
    render(<MyComponent title="Hello, World!" />);
    const titleElement = screen.getByText(/Hello, World!/i);
    expect(titleElement).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

3. Running Tests

You can run your tests using the following command:

npm test
Enter fullscreen mode Exit fullscreen mode

4. Mocking Functions

If your component interacts with functions (like API calls), you can mock them:

jest.mock('../api', () => ({
    fetchData: jest.fn(() => Promise.resolve({ data: 'mock data' })),
}));
Enter fullscreen mode Exit fullscreen mode

5. Testing Events

You can also simulate user interactions:

import userEvent from '@testing-library/user-event';

test('button click changes text', () => {
    render(<MyComponent />);
    const button = screen.getByRole('button', { name: /change text/i });
    userEvent.click(button);
    const updatedText = screen.getByText(/new text/i);
    expect(updatedText).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

6. Snapshot Testing

You can create a snapshot of your component for future reference:

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

test('matches snapshot', () => {
    const { asFragment } = render(<MyComponent title="Snapshot Test" />);
    expect(asFragment()).toMatchSnapshot();
});
Enter fullscreen mode Exit fullscreen mode

7. Code Coverage

To check code coverage, you can run:

npm test -- --coverage
Enter fullscreen mode Exit fullscreen mode

Conclusion

Jest, along with React Testing Library, provides a robust set of tools to test your React components effectively. You can test rendering, user interactions, and even API calls with mocks. As you build more complex components, these testing strategies will help maintain the reliability of your application.

💖 💪 🙅 🚩
imyusufakhtar
Md Yusuf

Posted on September 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Unit Testing React Components with Jest
unittesting Unit Testing React Components with Jest

September 30, 2024