Back to Repositories

Testing ImagePreview Component Rendering and Interactions in OpenHands

This test suite validates the ImagePreview component functionality in a React application, focusing on image rendering and removal capabilities. The tests ensure proper image display and interactive behavior through comprehensive unit testing.

Test Coverage Overview

The test suite provides thorough coverage of the ImagePreview component’s core functionality:

  • Image rendering verification with src attribute checking
  • Close button interaction and callback testing
  • Conditional rendering of close button based on prop availability
  • Edge case handling for optional onRemove prop

Implementation Analysis

The testing approach utilizes React Testing Library’s best practices for component testing. It employs userEvent for simulating user interactions and vitest’s mocking capabilities for callback verification. The tests follow the Arrange-Act-Assert pattern with clear separation of concerns.

Key patterns include role-based element queries and async event handling.

Technical Details

  • Testing Framework: Vitest
  • UI Testing: React Testing Library
  • User Interaction: @testing-library/user-event
  • Mocking: Vi.fn() for callback functions
  • Query Methods: getByRole, getByTestId, queryByRole

Best Practices Demonstrated

The test suite exemplifies several testing best practices including:

  • Accessibility-first testing with role-based queries
  • Isolation of component behavior
  • Proper async/await handling for user interactions
  • Meaningful test descriptions
  • Efficient mocking of callbacks

all-hands-ai/openhands

frontend/__tests__/components/image-preview.test.tsx

            
import { ImagePreview } from "#/components/features/images/image-preview";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";

describe("ImagePreview", () => {
  it("should render an image", () => {
    render(
      <ImagePreview src="https://example.com/image.jpg" onRemove={vi.fn} />,
    );
    const img = screen.getByRole("img");

    expect(screen.getByTestId("image-preview")).toBeInTheDocument();
    expect(img).toHaveAttribute("src", "https://example.com/image.jpg");
  });

  it("should call onRemove when the close button is clicked", async () => {
    const user = userEvent.setup();
    const onRemoveMock = vi.fn();
    render(
      <ImagePreview
        src="https://example.com/image.jpg"
        onRemove={onRemoveMock}
      />,
    );

    const closeButton = screen.getByRole("button");
    await user.click(closeButton);

    expect(onRemoveMock).toHaveBeenCalledOnce();
  });

  it("shoud not display the close button when onRemove is not provided", () => {
    render(<ImagePreview src="https://example.com/image.jpg" />);
    expect(screen.queryByRole("button")).not.toBeInTheDocument();
  });
});