DEV Community

Md Yusuf
Md Yusuf

Posted on

Integration Testing in React: Best Practices with Testing Library

Integration testing with React Testing Library involves testing how various components of your application work together. Here's a basic guide to get you started:

Setting Up

  1. Install Dependencies: Ensure you have the necessary libraries installed. If you haven't done so already, install React Testing Library and Jest:
   npm install --save-dev @testing-library/react @testing-library/jest-dom
Enter fullscreen mode Exit fullscreen mode
  1. Create a Test File: Typically, you would create a test file alongside the component you're testing, following a naming convention like ComponentName.test.js.

Writing Integration Tests

Here’s a step-by-step example of how to write an integration test:

Example Scenario

Let's say you have a simple form component that takes a user’s name and displays it when submitted.

Form.js:

import React, { useState } from 'react';

const Form = () => {
  const [name, setName] = useState('');
  const [submittedName, setSubmittedName] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    setSubmittedName(name);
    setName('');
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Enter your name"
        />
        <button type="submit">Submit</button>
      </form>
      {submittedName && <p>Hello, {submittedName}!</p>}
    </div>
  );
};

export default Form;
Enter fullscreen mode Exit fullscreen mode

Writing the Test

Form.test.js:

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

describe('Form Component', () => {
  test('displays the submitted name', () => {
    render(<Form />);

    // Input field and button
    const input = screen.getByPlaceholderText(/enter your name/i);
    const button = screen.getByRole('button', { name: /submit/i });

    // Simulate user typing and submitting the form
    fireEvent.change(input, { target: { value: 'John Doe' } });
    fireEvent.click(button);

    // Check if the submitted name is displayed
    expect(screen.getByText(/hello, john doe!/i)).toBeInTheDocument();
  });
});
Enter fullscreen mode Exit fullscreen mode

Explanation of the Test

  1. Render the Component: The render function mounts the Form component in a virtual DOM.

  2. Select Elements: Use screen to query elements. Here, we select the input and button using accessible queries.

  3. Simulate User Actions: Use fireEvent to simulate typing in the input field and clicking the submit button.

  4. Assert Expected Behavior: Finally, check if the expected output (the greeting message) appears in the document.

Running the Tests

Run your tests using the following command:

npm test
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Focus on User Interactions: Write tests that simulate how users interact with your app, not just the implementation details.
  • Keep Tests Isolated: Each test should focus on a specific functionality to ensure clarity and maintainability.
  • Use Descriptive Names: Make your test descriptions clear to convey what is being tested.

By following this approach, you can effectively test how different parts of your React application work together, ensuring a smoother user experience. Let me know if you need further assistance!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs