Users.test.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import { describe, it, expect, vi, beforeEach } from 'vitest';
  2. import { render, screen, waitFor } from '@testing-library/react';
  3. import userEvent from '@testing-library/user-event';
  4. import { TestWrapper } from '@/client/__test_utils__/test-render';
  5. import { UsersPage } from '../Users';
  6. import { userClient } from '@/client/api';
  7. // Mock the API client
  8. vi.mock('@/client/api', () => ({
  9. userClient: {
  10. $get: vi.fn(),
  11. $post: vi.fn(),
  12. ':id': {
  13. $put: vi.fn(),
  14. $delete: vi.fn()
  15. }
  16. }
  17. }));
  18. // Mock the toast notification
  19. vi.mock('sonner', () => ({
  20. toast: {
  21. success: vi.fn(),
  22. error: vi.fn()
  23. }
  24. }));
  25. describe('UsersPage Component', () => {
  26. const mockUsers = [
  27. {
  28. id: 1,
  29. username: 'admin',
  30. nickname: '管理员',
  31. email: 'admin@example.com',
  32. phone: '13800138000',
  33. name: '系统管理员',
  34. isDisabled: 0,
  35. createdAt: '2024-01-01T00:00:00.000Z',
  36. roles: [{ id: 1, name: 'admin' }]
  37. },
  38. {
  39. id: 2,
  40. username: 'user1',
  41. nickname: '用户1',
  42. email: 'user1@example.com',
  43. phone: '13900139000',
  44. name: '张三',
  45. isDisabled: 0,
  46. createdAt: '2024-01-02T00:00:00.000Z',
  47. roles: [{ id: 2, name: 'user' }]
  48. }
  49. ];
  50. beforeEach(() => {
  51. vi.clearAllMocks();
  52. // Mock successful API response - return a proper Response object
  53. (userClient.$get as any).mockImplementation(async (params: any) => {
  54. console.log('API called with params:', params);
  55. return {
  56. status: 200,
  57. ok: true,
  58. headers: new Headers({ 'content-type': 'application/json' }),
  59. json: async () => ({
  60. data: mockUsers,
  61. pagination: {
  62. total: 2,
  63. current: 1,
  64. pageSize: 10
  65. }
  66. })
  67. };
  68. });
  69. console.log('Mock setup complete');
  70. });
  71. it('应该渲染用户列表页面', async () => {
  72. render(
  73. <TestWrapper>
  74. <UsersPage />
  75. </TestWrapper>
  76. );
  77. // 检查页面标题
  78. expect(screen.getByText('用户管理')).toBeInTheDocument();
  79. // 检查创建用户按钮
  80. expect(screen.getByText('创建用户')).toBeInTheDocument();
  81. // 等待数据加载完成
  82. await waitFor(() => {
  83. expect(screen.getByText('admin')).toBeInTheDocument();
  84. expect(screen.getByText('user1')).toBeInTheDocument();
  85. }, { timeout: 10000 });
  86. // 检查API是否被调用
  87. expect(userClient.$get).toHaveBeenCalled();
  88. // 检查用户总数显示
  89. expect(screen.getByText(/共 2 位用户/)).toBeInTheDocument();
  90. });
  91. it('应该显示搜索框和过滤按钮', async () => {
  92. render(
  93. <TestWrapper>
  94. <UsersPage />
  95. </TestWrapper>
  96. );
  97. // 等待数据加载完成
  98. await waitFor(() => {
  99. expect(screen.getByText('admin')).toBeInTheDocument();
  100. }, { timeout: 10000 });
  101. // 检查搜索框
  102. expect(screen.getByPlaceholderText('搜索用户名、昵称或邮箱...')).toBeInTheDocument();
  103. // 检查搜索按钮
  104. expect(screen.getByText('搜索')).toBeInTheDocument();
  105. // 检查高级筛选按钮
  106. expect(screen.getByText('高级筛选')).toBeInTheDocument();
  107. });
  108. it('应该支持关键词搜索', async () => {
  109. const user = userEvent.setup();
  110. render(
  111. <TestWrapper>
  112. <UsersPage />
  113. </TestWrapper>
  114. );
  115. // 等待数据加载完成
  116. await waitFor(() => {
  117. expect(screen.getByText('admin')).toBeInTheDocument();
  118. }, { timeout: 10000 });
  119. // 在搜索框中输入关键词 - 使用paste来避免防抖中间状态
  120. const searchInput = screen.getByPlaceholderText('搜索用户名、昵称或邮箱...');
  121. await user.clear(searchInput);
  122. await user.click(searchInput);
  123. await user.paste('admin');
  124. // 等待防抖完成(300ms + 缓冲时间)
  125. await new Promise(resolve => setTimeout(resolve, 400));
  126. // 点击搜索按钮
  127. const searchButton = screen.getByText('搜索');
  128. await user.click(searchButton);
  129. // 验证API被调用正确的参数
  130. const calls = (userClient.$get as any).mock.calls;
  131. const lastCall = calls[calls.length - 1];
  132. // 检查搜索参数
  133. const queryParams = lastCall[0].query;
  134. expect(queryParams.page).toBe(1);
  135. expect(queryParams.pageSize).toBe(10);
  136. expect(queryParams.keyword).toBe('admin');
  137. });
  138. it('应该显示高级筛选面板', async () => {
  139. const user = userEvent.setup();
  140. render(
  141. <TestWrapper>
  142. <UsersPage />
  143. </TestWrapper>
  144. );
  145. // 等待数据加载完成
  146. await waitFor(() => {
  147. expect(screen.getByText('admin')).toBeInTheDocument();
  148. }, { timeout: 10000 });
  149. // 点击高级筛选按钮
  150. const filterButton = screen.getByText('高级筛选');
  151. await user.click(filterButton);
  152. // 检查筛选面板是否显示
  153. expect(screen.getByText('用户状态')).toBeInTheDocument();
  154. expect(screen.getByText('用户角色')).toBeInTheDocument();
  155. // 使用更具体的查询来避免与表格标题冲突
  156. expect(screen.getAllByText('创建时间')[0]).toBeInTheDocument();
  157. });
  158. it('应该显示加载骨架屏', async () => {
  159. // 清除之前的mock
  160. vi.clearAllMocks();
  161. // 模拟延迟响应
  162. (userClient.$get as any).mockImplementation(() =>
  163. new Promise(resolve => setTimeout(() => resolve({
  164. status: 200,
  165. ok: true,
  166. json: async () => ({
  167. data: mockUsers,
  168. pagination: { total: 2, current: 1, pageSize: 10 }
  169. })
  170. }), 100))
  171. );
  172. render(
  173. <TestWrapper>
  174. <UsersPage />
  175. </TestWrapper>
  176. );
  177. // 检查骨架屏是否显示
  178. expect(screen.getByText('用户管理')).toBeInTheDocument();
  179. expect(screen.getByText('创建用户')).toBeInTheDocument();
  180. // 检查骨架屏元素
  181. // 先检查所有元素来调试角色问题
  182. const allElements = screen.getAllByRole('generic');
  183. console.log('All elements with generic role:', allElements.length);
  184. // 尝试查找骨架屏元素
  185. const skeletons = screen.queryAllByRole('status');
  186. console.log('Elements with status role:', skeletons.length);
  187. // 如果找不到status角色,尝试通过data-slot查找
  188. if (skeletons.length === 0) {
  189. const skeletonElements = screen.queryAllByTestId('skeleton');
  190. if (skeletonElements.length === 0) {
  191. // 使用data-slot属性查找
  192. const slotSkeletons = document.querySelectorAll('[data-slot="skeleton"]');
  193. expect(slotSkeletons.length).toBeGreaterThan(0);
  194. } else {
  195. expect(skeletonElements.length).toBeGreaterThan(0);
  196. }
  197. } else {
  198. expect(skeletons.length).toBeGreaterThan(0);
  199. }
  200. // 等待数据加载完成
  201. await waitFor(() => {
  202. expect(screen.getByText('admin')).toBeInTheDocument();
  203. });
  204. // 检查骨架屏已消失
  205. const remainingSkeletons = screen.queryAllByRole('status');
  206. if (remainingSkeletons.length === 0) {
  207. // 也检查通过testid查找的骨架屏
  208. const remainingTestidSkeletons = screen.queryAllByTestId('skeleton');
  209. if (remainingTestidSkeletons.length === 0) {
  210. // 检查通过data-slot查找的骨架屏
  211. const remainingSlotSkeletons = document.querySelectorAll('[data-slot="skeleton"]');
  212. expect(remainingSlotSkeletons).toHaveLength(0);
  213. } else {
  214. expect(remainingTestidSkeletons).toHaveLength(0);
  215. }
  216. } else {
  217. expect(remainingSkeletons).toHaveLength(0);
  218. }
  219. });
  220. it('应该处理API错误', async () => {
  221. // 模拟API错误
  222. (userClient.$get as any).mockResolvedValue({
  223. status: 500,
  224. ok: false,
  225. json: async () => ({ error: 'Internal server error' })
  226. });
  227. render(
  228. <TestWrapper>
  229. <UsersPage />
  230. </TestWrapper>
  231. );
  232. // 检查页面仍然渲染
  233. expect(screen.getByText('用户管理')).toBeInTheDocument();
  234. expect(screen.getByText('创建用户')).toBeInTheDocument();
  235. // 等待加载完成(应该没有数据)
  236. await waitFor(() => {
  237. expect(screen.queryByText('admin')).not.toBeInTheDocument();
  238. expect(screen.queryByText('user1')).not.toBeInTheDocument();
  239. });
  240. });
  241. it('应该显示分页控件', async () => {
  242. // 模拟多页数据
  243. (userClient.$get as any).mockResolvedValue({
  244. status: 200,
  245. ok: true,
  246. json: async () => ({
  247. data: mockUsers,
  248. pagination: {
  249. total: 25,
  250. current: 1,
  251. pageSize: 10
  252. }
  253. })
  254. });
  255. render(
  256. <TestWrapper>
  257. <UsersPage />
  258. </TestWrapper>
  259. );
  260. await waitFor(() => {
  261. // 检查分页控件
  262. expect(screen.getByText('1')).toBeInTheDocument();
  263. expect(screen.getByText('2')).toBeInTheDocument();
  264. expect(screen.getByText('3')).toBeInTheDocument();
  265. });
  266. });
  267. });