刘嘉昕 | 07fee5f | 2025-06-09 17:18:47 +0800 | [diff] [blame] | 1 | import React from 'react'; |
| 2 | import { render, screen, waitFor } from '@testing-library/react'; |
| 3 | import { MemoryRouter, Route, Routes } from 'react-router-dom'; |
| 4 | import axios from 'axios'; |
| 5 | import TorrentDetail from '../components/Torrentdetail'; |
| 6 | import { vi } from 'vitest'; |
| 7 | |
| 8 | |
| 9 | beforeAll(() => { |
| 10 | Object.defineProperty(window, 'matchMedia', { |
| 11 | writable: true, |
| 12 | value: vi.fn().mockImplementation((query) => ({ |
| 13 | matches: false, |
| 14 | media: query, |
| 15 | onchange: null, |
| 16 | addListener: vi.fn(), |
| 17 | removeListener: vi.fn(), |
| 18 | addEventListener: vi.fn(), |
| 19 | removeEventListener: vi.fn(), |
| 20 | dispatchEvent: vi.fn(), |
| 21 | })), |
| 22 | }); |
| 23 | }); |
| 24 | |
| 25 | |
| 26 | // 模拟 axios |
| 27 | vi.mock('axios'); |
| 28 | |
| 29 | describe('TorrentDetail Page', () => { |
| 30 | const mockTorrent = { |
| 31 | torrentTitle: '测试种子', |
| 32 | uploader_id: 'uploader123', |
| 33 | description: '这是一个测试种子描述', |
| 34 | uploadTime: '2024-06-01T12:00:00Z', |
| 35 | torrentSize: 104857600, |
| 36 | downloadCount: 10, |
| 37 | dpi: '1080p', |
| 38 | caption: '简体中文', |
| 39 | lastseed: '2024-06-05T14:00:00Z', |
| 40 | coverImagePath: 'http://example.com/cover.jpg', |
| 41 | infoHash: 'abc123' |
| 42 | }; |
| 43 | |
| 44 | const mockSeeders = [ |
| 45 | { |
| 46 | username: 'Seeder1', |
| 47 | uploaded: 204857600, |
| 48 | uploadSpeed: 1048576, |
| 49 | downloaded: 102400, |
| 50 | downloadSpeed: 0, |
| 51 | client: 'qBittorrent', |
| 52 | lastEvent: '2024-06-06T11:22:00Z' |
| 53 | } |
| 54 | ]; |
| 55 | |
| 56 | beforeEach(() => { |
| 57 | axios.get.mockImplementation((url) => { |
| 58 | if (url.includes('/torrent/abc123/seeders')) { |
| 59 | return Promise.resolve({ data: mockSeeders }); |
| 60 | } |
| 61 | if (url.includes('/torrent/123')) { |
| 62 | return Promise.resolve({ data: mockTorrent }); |
| 63 | } |
| 64 | return Promise.reject(new Error('not found')); |
| 65 | }); |
| 66 | }); |
| 67 | |
| 68 | afterEach(() => { |
| 69 | vi.clearAllMocks(); |
| 70 | }); |
| 71 | |
| 72 | test('renders torrent detail and seeders correctly', async () => { |
| 73 | render( |
| 74 | <MemoryRouter initialEntries={['/torrent/123']}> |
| 75 | <Routes> |
| 76 | <Route path="/torrent/:id" element={<TorrentDetail />} /> |
| 77 | </Routes> |
| 78 | </MemoryRouter> |
| 79 | ); |
| 80 | |
| 81 | expect(document.querySelector('.ant-spin')).toBeInTheDocument(); |
| 82 | |
| 83 | |
| 84 | await waitFor(() => { |
| 85 | expect(screen.getByText('测试种子')).toBeInTheDocument(); |
| 86 | expect(screen.getByText('uploader123')).toBeInTheDocument(); |
| 87 | expect(screen.getByText(/1080p/)).toBeInTheDocument(); |
| 88 | expect(screen.getByText('Seeder1')).toBeInTheDocument(); |
| 89 | }); |
| 90 | }); |
| 91 | }); |