San3yuan | 03ab064 | 2025-04-29 18:00:25 +0800 | [diff] [blame^] | 1 | import React from 'react'; |
| 2 | import { render, screen, waitFor } from '@testing-library/react'; |
| 3 | import '@testing-library/jest-dom'; |
| 4 | import { useApi } from '@/hooks/request'; |
| 5 | import PostsPanel from '@/components/postsPanel/postsPanel'; |
| 6 | |
| 7 | // 模拟 useApi |
| 8 | jest.mock('@/hooks/request', () => ({ |
| 9 | useApi: jest.fn(() => ({ |
| 10 | data: [], // 默认返回空数组 |
| 11 | loading: false, |
| 12 | error: null, |
| 13 | })), |
| 14 | })); |
| 15 | describe('PostsPanel Component', () => { |
| 16 | const mockUseApi = useApi as jest.MockedFunction<typeof useApi>; |
| 17 | |
| 18 | it('renders the component with a title', () => { |
| 19 | // 渲染组件 |
| 20 | render(<PostsPanel name="热门帖子" url="/api/posts" limit={5} />); |
| 21 | |
| 22 | // 验证标题是否正确渲染 |
| 23 | expect(screen.getByText('热门帖子')).toBeInTheDocument(); |
| 24 | expect(screen.getByText('更多')).toBeInTheDocument(); |
| 25 | }); |
| 26 | |
| 27 | it('renders posts when data is available', async () => { |
| 28 | // 模拟 API 返回数据 |
| 29 | mockUseApi.mockReturnValue({ |
| 30 | data: [ |
| 31 | { title: 'Post 1', date: '2025-04-01' }, |
| 32 | { title: 'Post 2', date: '2025-04-02' }, |
| 33 | ], |
| 34 | }); |
| 35 | |
| 36 | // 渲染组件 |
| 37 | render(<PostsPanel name="热门帖子" url="/api/posts" limit={5} />); |
| 38 | |
| 39 | // 验证数据是否正确渲染 |
| 40 | await waitFor(() => { |
| 41 | expect(screen.getByText('Post 1')).toBeInTheDocument(); |
| 42 | expect(screen.getByText('2025-04-01')).toBeInTheDocument(); |
| 43 | expect(screen.getByText('Post 2')).toBeInTheDocument(); |
| 44 | expect(screen.getByText('2025-04-02')).toBeInTheDocument(); |
| 45 | }); |
| 46 | }); |
| 47 | |
| 48 | it('renders a message when no data is available', async () => { |
| 49 | // 模拟 API 返回空数据 |
| 50 | mockUseApi.mockReturnValue({ |
| 51 | data: [], |
| 52 | }); |
| 53 | |
| 54 | // 渲染组件 |
| 55 | render(<PostsPanel name="热门帖子" url="/api/posts" limit={5} />); |
| 56 | |
| 57 | // 验证无数据时的提示信息 |
| 58 | await waitFor(() => { |
| 59 | expect(screen.getByText('未查询到相关记录')).toBeInTheDocument(); |
| 60 | }); |
| 61 | }); |
| 62 | |
| 63 | it('handles loading state', () => { |
| 64 | // 模拟加载状态 |
| 65 | mockUseApi.mockReturnValue({ |
| 66 | data: null, |
| 67 | }); |
| 68 | |
| 69 | // 渲染组件 |
| 70 | render(<PostsPanel name="热门帖子" url="/api/posts" limit={5} />); |
| 71 | |
| 72 | // 验证组件是否正确渲染(可以根据需求添加加载状态的测试) |
| 73 | expect(screen.getByText('未查询到相关记录')).toBeInTheDocument(); |
| 74 | }); |
| 75 | }); |