| import React from 'react'; |
| import { render, screen, waitFor } from '@testing-library/react'; |
| import '@testing-library/jest-dom'; |
| import { useApi } from '@/hooks/request'; |
| import PostsPanel from '@/components/postsPanel/postsPanel'; |
| |
| // 模拟 useApi |
| jest.mock('@/hooks/request', () => ({ |
| useApi: jest.fn(() => ({ |
| data: [], // 默认返回空数组 |
| loading: false, |
| error: null, |
| })), |
| })); |
| describe('PostsPanel Component', () => { |
| const mockUseApi = useApi as jest.MockedFunction<typeof useApi>; |
| |
| it('renders the component with a title', () => { |
| // 渲染组件 |
| render(<PostsPanel name="热门帖子" url="/api/posts" limit={5} />); |
| |
| // 验证标题是否正确渲染 |
| expect(screen.getByText('热门帖子')).toBeInTheDocument(); |
| expect(screen.getByText('更多')).toBeInTheDocument(); |
| }); |
| |
| it('renders posts when data is available', async () => { |
| // 模拟 API 返回数据 |
| mockUseApi.mockReturnValue({ |
| data: [ |
| { title: 'Post 1', date: '2025-04-01' }, |
| { title: 'Post 2', date: '2025-04-02' }, |
| ], |
| }); |
| |
| // 渲染组件 |
| render(<PostsPanel name="热门帖子" url="/api/posts" limit={5} />); |
| |
| // 验证数据是否正确渲染 |
| await waitFor(() => { |
| expect(screen.getByText('Post 1')).toBeInTheDocument(); |
| expect(screen.getByText('2025-04-01')).toBeInTheDocument(); |
| expect(screen.getByText('Post 2')).toBeInTheDocument(); |
| expect(screen.getByText('2025-04-02')).toBeInTheDocument(); |
| }); |
| }); |
| |
| it('renders a message when no data is available', async () => { |
| // 模拟 API 返回空数据 |
| mockUseApi.mockReturnValue({ |
| data: [], |
| }); |
| |
| // 渲染组件 |
| render(<PostsPanel name="热门帖子" url="/api/posts" limit={5} />); |
| |
| // 验证无数据时的提示信息 |
| await waitFor(() => { |
| expect(screen.getByText('未查询到相关记录')).toBeInTheDocument(); |
| }); |
| }); |
| |
| it('handles loading state', () => { |
| // 模拟加载状态 |
| mockUseApi.mockReturnValue({ |
| data: null, |
| }); |
| |
| // 渲染组件 |
| render(<PostsPanel name="热门帖子" url="/api/posts" limit={5} />); |
| |
| // 验证组件是否正确渲染(可以根据需求添加加载状态的测试) |
| expect(screen.getByText('未查询到相关记录')).toBeInTheDocument(); |
| }); |
| }); |