import "../../../tests/web/test-utils";
import { render } from "@testing-library/react";
import { beforeEach, describe, expect, test, vi } from "bun:test";

import { ErrorBoundary } from "../../../src/web/components/ErrorBoundary";

// 一个正常组件
function NormalComponent() {
  return <div>Normal content</div>;
}

// 一个会抛错的组件
function ThrowError() {
  throw new Error("Test error");
  // TypeScript 需要返回值，虽然这里永远不会执行
  return null;
}

describe("ErrorBoundary", () => {
  let consoleErrorSpy: ReturnType<typeof vi.spyOn>;

  beforeEach(() => {
    consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {
      // Mock console.error to suppress error output during tests
    });
  });

  test("捕获子组件渲染错误并显示 fallback", () => {
    const { container } = render(
      <ErrorBoundary>
        <ThrowError />
      </ErrorBoundary>,
    );

    expect(container.firstChild).not.toBeNull();
  });

  test("正常渲染子组件", () => {
    const { container } = render(
      <ErrorBoundary>
        <NormalComponent />
      </ErrorBoundary>,
    );

    expect(container.firstChild).not.toBeNull();
  });

  test("刷新按钮不崩溃", () => {
    const { container } = render(
      <ErrorBoundary>
        <ThrowError />
      </ErrorBoundary>,
    );

    expect(container.firstChild).not.toBeNull();
  });

  test("错误时调用 console.error", () => {
    render(
      <ErrorBoundary>
        <ThrowError />
      </ErrorBoundary>,
    );

    expect(consoleErrorSpy).toHaveBeenCalled();
  });
});
