How To Test a React App with Jest and React Testing Library

Testing a React app with Jest and React Testing Library involves setting up a testing environment and writing test cases to ensure your components work as expected. Here's a step-by-step guide:

Setup:
  1. Install Jest and React Testing Library:

                    
                        npm install --save-dev jest @testing-library/react @testing-library/jest-dom
                    
                

  2. Configure Jest:

    Create a jest.config.js file at the root of your project or add configurations in package.json:

                    
                        {
                            "jest": {
                              "preset": "react-scripts"
                            }
                          }                      
                    
                

Writing Tests:
  1. Create a Test File:

    For a component named ExampleComponent, create a ExampleComponent.test.js file.

  2. Import Required Dependencies:

                    
                        import React from 'react';
                        import { render, screen } from '@testing-library/react';
                        import ExampleComponent from './ExampleComponent'; // Import the component to be tested                    
                    
                

  3. > Write Test Cases:
    • Render Test:

      Test if the component renders properly:

                              
                                  test('renders ExampleComponent', () => {
                                      render(<ExampleComponent />);
                                      const componentElement = screen.getByTestId('example-component'); // Use appropriate selector
                                      expect(componentElement).toBeInTheDocument();
                                    });                              
                              
                          

    • Interaction Test:

      Test user interaction:

                              
                                  test('clicking button changes text', () => {
                                      render(<ExampleComponent />);
                                      const buttonElement = screen.getByRole('button');
                                      const textElement = screen.getByTestId('text-element');
                                    
                                      expect(textElement).toHaveTextContent('Initial Text');
                                      userEvent.click(buttonElement);
                                      expect(textElement).toHaveTextContent('Updated Text');
                                    });                              
                              
                          

  4. Run Tests:

    Execute tests using the Jest CLI or through your package.json script:

                    
                        npm test
                    
                

Tips:
  • Queries: Use screen from @testing-library/react to query elements by text, role, label, or any other accessible way.
  • Assertions: Leverage expect from Jest to make assertions about the DOM elements.
  • Async Testing: For async code, use async/await or return Promises within your tests.
Mocking:
  • Mocking Dependencies: Use jest.mock() to mock external dependencies like API calls or modules.
  • Mock Functions: Use jest.fn() to create mock functions and spy on function calls.
Cleanup:
  • Cleanup After Tests: If your tests render components that might affect other tests, use cleanup() from @testing-library/react to clean up after each test.

This setup and structure provide a solid foundation for testing React components. React Testing Library focuses on testing components as users would interact with them, promoting good testing practices and maintainable tests.

How To Set Up an Ubuntu Server on a DigitalOcean Droplet

Setting up an Ubuntu Server on a DigitalOcean Droplet is a common task for deploying web applications, hosting websites, running databases, and more. Here's a detailed guide to help you through the process. Setting up an Ubuntu server on a DigitalOce …

read more

How can you link an external CSS stylesheet to an HTML document

To link an external CSS stylesheet to an HTML document, you can use the <link> element in the <head> section of your HTML document. Here's how you can do it: Ensure that the path specified in the href attribute is correct and that the CSS …

read more