import { act, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ThreadHistoryStatus } from "@/components/thread/ThreadHistoryStatus";
afterEach(() => {
vi.useRealTimers();
});
describe("ThreadHistoryStatus", () => {
it("delays the loading indicator so fast history requests do not flash", () => {
vi.useFakeTimers();
render();
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
act(() => vi.advanceTimersByTime(179));
expect(screen.queryByText("Loading earlier messages…")).not.toBeInTheDocument();
act(() => vi.advanceTimersByTime(1));
expect(screen.getByText("Loading earlier messages…")).toHaveClass("sr-only");
expect(screen.getByRole("status").querySelector("svg")).toHaveClass("animate-spin");
});
it("cancels the delay on completion and starts a fresh delay for the next request", () => {
vi.useFakeTimers();
const props = { error: null, onRetry: vi.fn() };
const { rerender } = render();
act(() => vi.advanceTimersByTime(100));
rerender();
act(() => vi.advanceTimersByTime(500));
expect(screen.getByRole("status")).toBeEmptyDOMElement();
rerender();
act(() => vi.advanceTimersByTime(180));
expect(screen.getByText("Loading earlier messages…")).toHaveClass("sr-only");
expect(screen.getByRole("status").querySelector("svg")).toHaveClass("animate-spin");
rerender();
expect(screen.getByRole("status")).toBeEmptyDOMElement();
rerender();
expect(screen.getByRole("status")).toBeEmptyDOMElement();
});
it("offers an explicit retry after loading earlier history fails", () => {
const onRetry = vi.fn();
render();
expect(screen.getByText("Loading failed.")).toBeVisible();
expect(screen.getByRole("status").parentElement).toHaveClass("thread-message-row");
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(onRetry).toHaveBeenCalledTimes(1);
});
});