area-management.integration.test.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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('AreaManagement Integration Tests', () => {
  71. beforeEach(() => {
  72. vi.clearAllMocks();
  73. });
  74. it('should render area management component with title', 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('should show loading state when fetching data', 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('should show empty state when no data', 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('should open create dialog when clicking add button', 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('should handle API errors gracefully', 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('should complete create and delete workflow', 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('should handle API errors in CRUD operations', 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. });