刘嘉昕 | 33b9f17 | 2025-06-09 17:23:06 +0800 | [diff] [blame] | 1 | // TorrentList.test.jsx |
| 2 | import React from 'react'; |
| 3 | import { render, screen, fireEvent, waitFor } from '@testing-library/react'; |
| 4 | import TorrentList from '../components/TorrentList'; |
| 5 | import axios from 'axios'; |
| 6 | import { MemoryRouter } from 'react-router-dom'; // ✅ 引入 MemoryRouter |
| 7 | |
| 8 | |
| 9 | import { vi } from 'vitest'; |
| 10 | beforeAll(() => { |
| 11 | Object.defineProperty(window, 'matchMedia', { |
| 12 | writable: true, |
| 13 | value: vi.fn().mockImplementation((query) => ({ |
| 14 | matches: false, |
| 15 | media: query, |
| 16 | onchange: null, |
| 17 | addListener: vi.fn(), |
| 18 | removeListener: vi.fn(), |
| 19 | addEventListener: vi.fn(), |
| 20 | removeEventListener: vi.fn(), |
| 21 | dispatchEvent: vi.fn(), |
| 22 | })), |
| 23 | }); |
| 24 | }); |
| 25 | |
| 26 | vi.mock('axios'); |
| 27 | |
| 28 | |
| 29 | |
| 30 | describe('TorrentList - 搜索功能', () => { |
| 31 | test('搜索关键词后应正确调用接口并显示结果', async () => { |
| 32 | const mockTorrents = [ |
| 33 | { id: 1, title: '测试种子1', uploader_id: 123 }, |
| 34 | { id: 2, title: '测试种子2', uploader_id: 456 }, |
| 35 | ]; |
| 36 | |
| 37 | axios.get.mockResolvedValueOnce({ data: mockTorrents }); |
| 38 | |
| 39 | render( |
| 40 | <MemoryRouter> |
| 41 | <TorrentList /> |
| 42 | </MemoryRouter> |
| 43 | ); |
| 44 | |
| 45 | // 输入关键词 |
| 46 | const input = screen.getByPlaceholderText(/搜索种子/i); |
| 47 | fireEvent.change(input, { target: { value: '测试' } }); |
| 48 | |
| 49 | // 模拟点击搜索按钮 |
| 50 | const button = screen.getByRole('button', { name: /搜\s*索/i }); |
| 51 | fireEvent.click(button); |
| 52 | |
| 53 | |
| 54 | // 等待并断言结果被渲染 |
| 55 | await waitFor(() => { |
| 56 | expect(axios.get).toHaveBeenCalledWith( |
| 57 | 'http://localhost:8080/torrent/search', |
| 58 | { params: { keyword: '测试' } } |
| 59 | ); |
| 60 | }); |
| 61 | |
| 62 | // expect(await screen.findByText('测试种子1')).toBeInTheDocument(); |
| 63 | // expect(await screen.findByText('测试种子2')).toBeInTheDocument(); |
| 64 | }); |
| 65 | }); |