area-management.integration.test.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. import React from 'react';
  2. import { describe, it, expect, vi, beforeEach } from 'vitest';
  3. import { render, screen, waitFor, fireEvent } from '@testing-library/react';
  4. import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
  5. import { BrowserRouter } from 'react-router';
  6. import { AreaManagement } from '../../src/components/AreaManagement';
  7. import { areaClient } from '../../src/api/areaClient';
  8. // 完整的mock响应对象 - 按照用户UI包规范
  9. const createMockResponse = (status: number, data?: any) => ({
  10. status,
  11. ok: status >= 200 && status < 300,
  12. body: null,
  13. bodyUsed: false,
  14. statusText: status === 200 ? 'OK' : status === 201 ? 'Created' : status === 204 ? 'No Content' : 'Error',
  15. headers: new Headers(),
  16. url: '',
  17. redirected: false,
  18. type: 'basic' as ResponseType,
  19. json: async () => data || {},
  20. text: async () => '',
  21. blob: async () => new Blob(),
  22. arrayBuffer: async () => new ArrayBuffer(0),
  23. formData: async () => new FormData(),
  24. clone: function() { return this; }
  25. });
  26. // Mock areaClient - 按照用户UI包规范
  27. vi.mock('../../src/api/areaClient', () => {
  28. const mockAreaClient = {
  29. index: {
  30. $get: vi.fn(() => Promise.resolve({ status: 200, body: null })),
  31. $post: vi.fn(() => Promise.resolve({ status: 201, body: null })),
  32. },
  33. ':id': {
  34. $put: vi.fn(() => Promise.resolve({ status: 200, body: null })),
  35. $delete: vi.fn(() => Promise.resolve({ status: 204, body: null })),
  36. },
  37. };
  38. const mockAreaClientManager = {
  39. get: vi.fn(() => mockAreaClient),
  40. };
  41. return {
  42. areaClientManager: mockAreaClientManager,
  43. areaClient: mockAreaClient,
  44. };
  45. });
  46. // Mock sonner toast
  47. vi.mock('sonner', () => ({
  48. toast: {
  49. success: vi.fn(),
  50. error: vi.fn()
  51. }
  52. }));
  53. // Test wrapper component
  54. const TestWrapper: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  55. const queryClient = new QueryClient({
  56. defaultOptions: {
  57. queries: {
  58. retry: false,
  59. },
  60. },
  61. });
  62. return (
  63. <BrowserRouter>
  64. <QueryClientProvider client={queryClient}>
  65. {children}
  66. </QueryClientProvider>
  67. </BrowserRouter>
  68. );
  69. };
  70. describe('区域管理集成测试', () => {
  71. beforeEach(() => {
  72. vi.clearAllMocks();
  73. });
  74. it('应该渲染区域管理组件并显示标题', async () => {
  75. // Mock successful API response for province data
  76. (areaClient.index.$get as any).mockResolvedValueOnce(createMockResponse(200, {
  77. data: [
  78. {
  79. id: 1,
  80. tenantId: 1,
  81. name: '北京市',
  82. code: '110000',
  83. level: 1,
  84. parentId: null,
  85. isDisabled: 0
  86. }
  87. ]
  88. }));
  89. render(
  90. <TestWrapper>
  91. <AreaManagement />
  92. </TestWrapper>
  93. );
  94. // Check if title is rendered
  95. expect(screen.getByText('省市区树形管理')).toBeInTheDocument();
  96. expect(screen.getByText('异步加载树形结构,高效管理省市区数据')).toBeInTheDocument();
  97. // Wait for loading to complete
  98. await waitFor(() => {
  99. expect(screen.getByText('北京市')).toBeInTheDocument();
  100. });
  101. });
  102. it('应该在获取数据时显示加载状态', async () => {
  103. // Mock delayed API response
  104. (areaClient.index.$get as any).mockImplementationOnce(() =>
  105. new Promise(resolve => setTimeout(() => resolve(createMockResponse(200, { data: [] })), 100))
  106. );
  107. render(
  108. <TestWrapper>
  109. <AreaManagement />
  110. </TestWrapper>
  111. );
  112. // Check if loading state is shown
  113. expect(screen.getByText('加载中...')).toBeInTheDocument();
  114. // Wait for loading to complete
  115. await waitFor(() => {
  116. expect(screen.queryByText('加载中...')).not.toBeInTheDocument();
  117. });
  118. });
  119. it('应该在无数据时显示空状态', async () => {
  120. // Mock empty API response
  121. (areaClient.index.$get as any).mockResolvedValueOnce(createMockResponse(200, { data: [] }));
  122. render(
  123. <TestWrapper>
  124. <AreaManagement />
  125. </TestWrapper>
  126. );
  127. // Wait for empty state to appear
  128. await waitFor(() => {
  129. expect(screen.getByText('暂无数据')).toBeInTheDocument();
  130. });
  131. });
  132. it('应该在点击新增按钮时打开创建对话框', async () => {
  133. // Mock successful API response
  134. (areaClient.index.$get as any).mockResolvedValueOnce(createMockResponse(200, {
  135. data: [
  136. {
  137. id: 1,
  138. tenantId: 1,
  139. name: '北京市',
  140. code: '110000',
  141. level: 1,
  142. parentId: null,
  143. isDisabled: 0
  144. }
  145. ]
  146. }));
  147. render(
  148. <TestWrapper>
  149. <AreaManagement />
  150. </TestWrapper>
  151. );
  152. // Wait for data to load
  153. await waitFor(() => {
  154. expect(screen.getByText('北京市')).toBeInTheDocument();
  155. });
  156. // Click add button
  157. const addButton = screen.getByText('新增省');
  158. fireEvent.click(addButton);
  159. // Check if dialog opens
  160. await waitFor(() => {
  161. expect(screen.getByRole('heading', { name: '新增省' })).toBeInTheDocument();
  162. expect(screen.getByText('填写省信息')).toBeInTheDocument();
  163. });
  164. });
  165. it('应该优雅地处理API错误', async () => {
  166. // Mock API error
  167. (areaClient.index.$get as any).mockRejectedValueOnce(new Error('API Error'));
  168. render(
  169. <TestWrapper>
  170. <AreaManagement />
  171. </TestWrapper>
  172. );
  173. // Wait for error state
  174. await waitFor(() => {
  175. // Component should handle errors gracefully
  176. expect(screen.getByText('省市区树形管理')).toBeInTheDocument();
  177. });
  178. });
  179. it('应该完成创建和删除工作流程', async () => {
  180. const { toast } = await import('sonner');
  181. // Mock initial areas data
  182. const mockAreas = {
  183. data: [
  184. {
  185. id: 1,
  186. tenantId: 1,
  187. name: '北京市',
  188. code: '110000',
  189. level: 1,
  190. parentId: null,
  191. isDisabled: 0
  192. }
  193. ]
  194. };
  195. // Mock initial data fetch
  196. (areaClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockAreas));
  197. render(
  198. <TestWrapper>
  199. <AreaManagement />
  200. </TestWrapper>
  201. );
  202. // Wait for initial data to load
  203. await waitFor(() => {
  204. expect(screen.getByText('北京市')).toBeInTheDocument();
  205. });
  206. // Test create area
  207. const addButton = screen.getByText('新增省');
  208. fireEvent.click(addButton);
  209. // Wait for create dialog
  210. await waitFor(() => {
  211. expect(screen.getByRole('heading', { name: '新增省' })).toBeInTheDocument();
  212. });
  213. // Fill create form
  214. const nameInput = screen.getByPlaceholderText('输入区域名称');
  215. const codeInput = screen.getByPlaceholderText('输入行政区划代码');
  216. fireEvent.change(nameInput, { target: { value: '上海市' } });
  217. fireEvent.change(codeInput, { target: { value: '310000' } });
  218. // Mock successful creation
  219. (areaClient.index.$post as any).mockResolvedValue(createMockResponse(201, { id: 2, name: '上海市' }));
  220. const submitButton = screen.getByText('创建');
  221. fireEvent.click(submitButton);
  222. await waitFor(() => {
  223. expect(areaClient.index.$post).toHaveBeenCalledWith({
  224. json: {
  225. tenantId: 1,
  226. name: '上海市',
  227. code: '310000',
  228. level: 1,
  229. parentId: null,
  230. isDisabled: 0
  231. }
  232. });
  233. expect(toast.success).toHaveBeenCalledWith('省市区创建成功');
  234. });
  235. // 跳过编辑操作测试,专注于创建和删除操作
  236. // Test delete area
  237. const deleteButtons = screen.getAllByRole('button', { name: '删除' });
  238. fireEvent.click(deleteButtons[0]);
  239. // Confirm deletion
  240. expect(screen.getByRole('heading', { name: '确认删除' })).toBeInTheDocument();
  241. // Mock successful deletion
  242. (areaClient[':id']['$delete'] as any).mockResolvedValue({
  243. status: 204,
  244. });
  245. // 查找删除确认按钮
  246. const confirmDeleteButton = screen.getByRole('button', { name: '确认删除' });
  247. fireEvent.click(confirmDeleteButton);
  248. await waitFor(() => {
  249. expect(areaClient[':id']['$delete']).toHaveBeenCalledWith({
  250. param: { id: 1 },
  251. });
  252. expect(toast.success).toHaveBeenCalledWith('省市区删除成功');
  253. });
  254. });
  255. it('应该处理CRUD操作中的API错误', async () => {
  256. const { areaClient } = await import('../../src/api/areaClient');
  257. const { toast } = await import('sonner');
  258. // Mock initial data
  259. const mockAreas = {
  260. data: [
  261. {
  262. id: 1,
  263. tenantId: 1,
  264. name: '北京市',
  265. code: '110000',
  266. level: 1,
  267. parentId: null,
  268. isDisabled: 0
  269. }
  270. ]
  271. };
  272. (areaClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockAreas));
  273. render(
  274. <TestWrapper>
  275. <AreaManagement />
  276. </TestWrapper>
  277. );
  278. // Wait for data to load
  279. await waitFor(() => {
  280. expect(screen.getByText('北京市')).toBeInTheDocument();
  281. });
  282. // Test create area error
  283. const addButton = screen.getByText('新增省');
  284. fireEvent.click(addButton);
  285. await waitFor(() => {
  286. expect(screen.getByRole('heading', { name: '新增省' })).toBeInTheDocument();
  287. });
  288. const nameInput = screen.getByPlaceholderText('输入区域名称');
  289. const codeInput = screen.getByPlaceholderText('输入行政区划代码');
  290. fireEvent.change(nameInput, { target: { value: '上海市' } });
  291. fireEvent.change(codeInput, { target: { value: '310000' } });
  292. // Mock creation error
  293. (areaClient.index.$post as any).mockRejectedValue(new Error('Creation failed'));
  294. const submitButton = screen.getByText('创建');
  295. fireEvent.click(submitButton);
  296. await waitFor(() => {
  297. expect(toast.error).toHaveBeenCalledWith('创建失败,请重试');
  298. });
  299. });
  300. it('应该支持4级区域层级(省→市→区→乡镇)', async () => {
  301. // Mock initial data with all levels
  302. const mockAreas = {
  303. data: [
  304. {
  305. id: 1,
  306. tenantId: 1,
  307. name: '北京市',
  308. code: '110000',
  309. level: 1,
  310. parentId: null,
  311. isDisabled: 0
  312. },
  313. {
  314. id: 2,
  315. tenantId: 1,
  316. name: '北京市市辖区',
  317. code: '110100',
  318. level: 2,
  319. parentId: 1,
  320. isDisabled: 0
  321. },
  322. {
  323. id: 3,
  324. tenantId: 1,
  325. name: '朝阳区',
  326. code: '110105',
  327. level: 3,
  328. parentId: 2,
  329. isDisabled: 0
  330. },
  331. {
  332. id: 4,
  333. tenantId: 1,
  334. name: '建国门街道',
  335. code: '110105001',
  336. level: 4,
  337. parentId: 3,
  338. isDisabled: 0
  339. }
  340. ]
  341. };
  342. (areaClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockAreas));
  343. render(
  344. <TestWrapper>
  345. <AreaManagement />
  346. </TestWrapper>
  347. );
  348. // Wait for all level data to load
  349. await waitFor(() => {
  350. expect(screen.getByText('北京市')).toBeInTheDocument();
  351. expect(screen.getByText('北京市市辖区')).toBeInTheDocument();
  352. expect(screen.getByText('朝阳区')).toBeInTheDocument();
  353. expect(screen.getByText('建国门街道')).toBeInTheDocument();
  354. });
  355. // Verify all levels are displayed correctly
  356. expect(screen.getByText('北京市')).toBeInTheDocument();
  357. expect(screen.getByText('北京市市辖区')).toBeInTheDocument();
  358. expect(screen.getByText('朝阳区')).toBeInTheDocument();
  359. expect(screen.getByText('建国门街道')).toBeInTheDocument();
  360. });
  361. it('应该成功创建4级区域(乡镇)', async () => {
  362. const { toast } = await import('sonner');
  363. // Mock initial data with district
  364. const mockAreas = {
  365. data: [
  366. {
  367. id: 3,
  368. tenantId: 1,
  369. name: '朝阳区',
  370. code: '110105',
  371. level: 3,
  372. parentId: 2,
  373. isDisabled: 0
  374. }
  375. ]
  376. };
  377. (areaClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockAreas));
  378. render(
  379. <TestWrapper>
  380. <AreaManagement />
  381. </TestWrapper>
  382. );
  383. // Wait for data to load
  384. await waitFor(() => {
  385. expect(screen.getByText('朝阳区')).toBeInTheDocument();
  386. });
  387. // Click add child button for district
  388. const addChildButtons = screen.getAllByRole('button', { name: '新增乡镇' });
  389. fireEvent.click(addChildButtons[0]);
  390. // Check if town creation dialog opens
  391. await waitFor(() => {
  392. expect(screen.getByRole('heading', { name: '新增乡镇' })).toBeInTheDocument();
  393. expect(screen.getByText('在区县 "朝阳区" 下新增街道/乡镇')).toBeInTheDocument();
  394. });
  395. // Fill town form
  396. const nameInput = screen.getByPlaceholderText('输入区域名称');
  397. const codeInput = screen.getByPlaceholderText('输入行政区划代码');
  398. fireEvent.change(nameInput, { target: { value: '建国门街道' } });
  399. fireEvent.change(codeInput, { target: { value: '110105001' } });
  400. // Mock successful town creation
  401. (areaClient.index.$post as any).mockResolvedValue(createMockResponse(201, { id: 4, name: '建国门街道' }));
  402. const submitButton = screen.getByText('创建');
  403. fireEvent.click(submitButton);
  404. await waitFor(() => {
  405. expect(areaClient.index.$post).toHaveBeenCalledWith({
  406. json: {
  407. tenantId: 1,
  408. name: '建国门街道',
  409. code: '110105001',
  410. level: 4,
  411. parentId: 3,
  412. isDisabled: 0
  413. }
  414. });
  415. expect(toast.success).toHaveBeenCalledWith('省市区创建成功');
  416. });
  417. });
  418. it('应该处理4级区域状态切换', async () => {
  419. const { toast } = await import('sonner');
  420. // Mock initial data with town
  421. const mockAreas = {
  422. data: [
  423. {
  424. id: 4,
  425. tenantId: 1,
  426. name: '建国门街道',
  427. code: '110105001',
  428. level: 4,
  429. parentId: 3,
  430. isDisabled: 0
  431. }
  432. ]
  433. };
  434. (areaClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockAreas));
  435. render(
  436. <TestWrapper>
  437. <AreaManagement />
  438. </TestWrapper>
  439. );
  440. // Wait for data to load
  441. await waitFor(() => {
  442. expect(screen.getByText('建国门街道')).toBeInTheDocument();
  443. });
  444. // Click toggle status button for town
  445. const toggleButtons = screen.getAllByRole('button', { name: '禁用' });
  446. fireEvent.click(toggleButtons[0]);
  447. // Check if status toggle dialog opens
  448. await waitFor(() => {
  449. expect(screen.getByRole('heading', { name: '禁用确认' })).toBeInTheDocument();
  450. expect(screen.getByText('确定要禁用省市区 "建国门街道" 吗?')).toBeInTheDocument();
  451. });
  452. // Mock successful status toggle
  453. (areaClient[':id'].$put as any).mockResolvedValue(createMockResponse(200));
  454. const confirmButton = screen.getByRole('button', { name: '确认' });
  455. fireEvent.click(confirmButton);
  456. await waitFor(() => {
  457. expect(areaClient[':id'].$put).toHaveBeenCalledWith({
  458. param: { id: 4 },
  459. json: { isDisabled: 1 }
  460. });
  461. expect(toast.success).toHaveBeenCalledWith('省市区禁用成功');
  462. });
  463. });
  464. it('应该成功删除4级区域(乡镇)', async () => {
  465. const { toast } = await import('sonner');
  466. // Mock initial data with town
  467. const mockAreas = {
  468. data: [
  469. {
  470. id: 4,
  471. tenantId: 1,
  472. name: '建国门街道',
  473. code: '110105001',
  474. level: 4,
  475. parentId: 3,
  476. isDisabled: 0
  477. }
  478. ]
  479. };
  480. (areaClient.index.$get as any).mockResolvedValue(createMockResponse(200, mockAreas));
  481. render(
  482. <TestWrapper>
  483. <AreaManagement />
  484. </TestWrapper>
  485. );
  486. // Wait for data to load
  487. await waitFor(() => {
  488. expect(screen.getByText('建国门街道')).toBeInTheDocument();
  489. });
  490. // Click delete button for town
  491. const deleteButtons = screen.getAllByRole('button', { name: '删除' });
  492. fireEvent.click(deleteButtons[0]);
  493. // Check if delete confirmation dialog opens
  494. await waitFor(() => {
  495. expect(screen.getByRole('heading', { name: '确认删除' })).toBeInTheDocument();
  496. expect(screen.getByText('确定要删除省市区 "建国门街道" 吗?此操作不可恢复。')).toBeInTheDocument();
  497. });
  498. // Mock successful deletion
  499. (areaClient[':id'].$delete as any).mockResolvedValue(createMockResponse(204));
  500. const confirmDeleteButton = screen.getByRole('button', { name: '确认删除' });
  501. fireEvent.click(confirmDeleteButton);
  502. await waitFor(() => {
  503. expect(areaClient[':id'].$delete).toHaveBeenCalledWith({
  504. param: { id: 4 }
  505. });
  506. expect(toast.success).toHaveBeenCalledWith('省市区删除成功');
  507. });
  508. });
  509. });