test: 重构测试体系 — 建立组件测试层、补充后端测试、清理低质量测试
- 新增 jsdom + @testing-library/react 组件测试环境 - 新增 12 个组件测试,覆盖所有前端组件 - 补充后端 middleware 和 helpers 单元测试 - 删除伪测试 use-target-detail-logic.test.ts - 精简过度枚举的 color-threshold.test.ts - 新增 bunfig.toml 配置测试 preload - 更新 DEVELOPMENT.md 测试章节 - 安装 @types/jsdom 修复类型声明
This commit is contained in:
67
tests/web/components/ErrorBoundary.test.tsx
Normal file
67
tests/web/components/ErrorBoundary.test.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user