Chats.test.tsx 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { fireEvent, render, screen, waitFor } from '@testing-library/react';
  2. import { beforeEach, expect, it, vi } from 'vitest';
  3. import { history } from '@umijs/max';
  4. import ChatsPage from '@/pages/Chats';
  5. import { apiRequest } from '@/services/api';
  6. vi.mock('@/services/api', () => ({ apiRequest: vi.fn() }));
  7. beforeEach(() => vi.clearAllMocks());
  8. const chatPage = {
  9. items: [
  10. {
  11. chat_id: '-100123',
  12. title: '测试运营群',
  13. username: 'ops_test',
  14. type: 'supergroup',
  15. accessible: true,
  16. member_count: 42,
  17. bot_status: 'administrator',
  18. },
  19. {
  20. chat_id: '-100456',
  21. title: '机器人已退出的群',
  22. type: 'supergroup',
  23. accessible: false,
  24. member_count: 8,
  25. bot_status: 'left',
  26. },
  27. ],
  28. total: 2,
  29. page: 1,
  30. page_size: 20,
  31. };
  32. it('可用群进入管理页,不可用群提供移除入口', async () => {
  33. vi.mocked(apiRequest).mockResolvedValue(chatPage);
  34. render(<ChatsPage />);
  35. expect(await screen.findByText('测试运营群')).toBeInTheDocument();
  36. fireEvent.click(screen.getByRole('button', { name: '管理' }));
  37. expect(history.push).toHaveBeenCalledWith('/chats/-100123');
  38. expect(
  39. screen.getByRole('button', { name: '移除不可用群 机器人已退出的群' }),
  40. ).toBeInTheDocument();
  41. await waitFor(() => expect(apiRequest).toHaveBeenCalledTimes(1));
  42. });
  43. it('确认后移除不可用群并刷新列表', async () => {
  44. vi.mocked(apiRequest)
  45. .mockResolvedValueOnce(chatPage)
  46. .mockResolvedValueOnce({ removed: true })
  47. .mockResolvedValueOnce({ ...chatPage, items: chatPage.items.slice(0, 1), total: 1 });
  48. render(<ChatsPage />);
  49. fireEvent.click(
  50. await screen.findByRole('button', { name: '移除不可用群 机器人已退出的群' }),
  51. );
  52. expect(await screen.findByText('仅移除当前 Bot 的管理列表记录,不会删除群消息、积分或抽奖数据;Bot 以后重新在群里活动时会再次出现。')).toBeInTheDocument();
  53. fireEvent.click(screen.getByRole('button', { name: /^移\s*除$/ }));
  54. await waitFor(() => {
  55. expect(apiRequest).toHaveBeenNthCalledWith(
  56. 2,
  57. '/chats/-100456',
  58. { method: 'DELETE' },
  59. );
  60. expect(apiRequest).toHaveBeenCalledTimes(3);
  61. });
  62. });