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
Implementation Analysis
Technical Details
Best Practices Demonstrated
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();
});
});