refactor: 优化组件并添加测试覆盖
- 创建 CLAUDE.md 项目开发指导文档 - 提取公共常量到 components/constants.ts - 修复 TimestampToDatetime 重复插件扩展问题 - 修复 DatetimeToTimestamp 时区解析问题 - 优化 RoutePersistence 移除不必要依赖 - 添加 Vitest 测试框架配置 - 为所有组件编写单元测试 (16个测试用例) - 更新 .gitignore 忽略测试结果目录 Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import Navbar from '../Navbar';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
const mockItems = [
|
||||
{ path: '/', label: '首页', element: <div>首页</div> },
|
||||
{ path: '/timestamp', label: '时间戳', element: <div>时间戳</div> },
|
||||
];
|
||||
|
||||
const renderWithRouter = (initialPath = '/', items = mockItems) => {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialPath]}>
|
||||
<Navbar items={items} />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('Navbar', () => {
|
||||
beforeEach(() => {
|
||||
// 模拟 useMediaQuery 以确保大屏幕行为
|
||||
Object.defineProperty(window, 'matchMedia', {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query) => ({
|
||||
matches: query === '(min-width:768px)',
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
it('应该正确渲染所有导航项(大屏幕)', () => {
|
||||
renderWithRouter();
|
||||
mockItems.forEach((item) => {
|
||||
expect(screen.getByText(item.label)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('没有提供 items 时应该正常渲染', () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<Navbar />
|
||||
</MemoryRouter>,
|
||||
);
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user