inbox-navigation.test.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import { App as AntApp, ConfigProvider } from 'antd';
  2. import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
  3. import userEvent from '@testing-library/user-event';
  4. import { createMemoryRouter, RouterProvider } from 'react-router-dom';
  5. import { afterEach, describe, expect, it, vi } from 'vitest';
  6. import { AppContext, type AppContextValue } from '../../src/frontend/app-context';
  7. import { I18nProvider } from '../../src/frontend/i18n/react';
  8. import { detailHistoryState } from '../../src/frontend/navigation-state';
  9. import { api } from '../../src/frontend/services/api';
  10. import { mailhubTheme } from '../../src/frontend/theme';
  11. import type { Domain, InboundMailbox, InboundMessage, RuntimeConfig } from '../../src/frontend/types';
  12. import Inbox from '../../src/pages/Inbox';
  13. describe('Inbox detail return path', () => {
  14. afterEach(() => vi.restoreAllMocks());
  15. it('keeps the original list history when another message is selected from an open detail', async () => {
  16. const user = userEvent.setup();
  17. const first = messageFixture(9, 1, 'Sent', 'First message');
  18. const second = messageFixture(10, 1, 'Sent', 'Second message');
  19. mockInboxApis([mailboxFixture(1)], [first, second]);
  20. vi.spyOn(api, 'inboundMessage').mockImplementation(async (id) => ({ message: id === second.id ? second : first }));
  21. const listPath = '/inbox?mailboxId=1&folder=Sent&page=2';
  22. const router = createInboxRouter(['/overview', listPath], 1);
  23. renderRouter(router);
  24. await user.click(await screen.findByRole('button', { name: 'First message · sender@example.test' }));
  25. await waitFor(() => expect(router.state.location.pathname).toBe('/inbox/messages/9'));
  26. expect(detailHistoryState(router.state.location.state)).toEqual({ listPath, depth: 1, origin: 'list' });
  27. fireEvent.click(screen.getByRole('button', { name: 'Second message · sender@example.test' }));
  28. await waitFor(() => expect(router.state.location.pathname).toBe('/inbox/messages/10'));
  29. expect(detailHistoryState(router.state.location.state)).toEqual({ listPath, depth: 2, origin: 'list' });
  30. fireEvent.click(screen.getByRole('button', { name: 'Close' }));
  31. await waitFor(() => expect(`${router.state.location.pathname}${router.state.location.search}`).toBe(listPath));
  32. await act(async () => {
  33. await router.navigate(-1);
  34. });
  35. expect(router.state.location.pathname).toBe('/overview');
  36. });
  37. it('keeps direct detail tabs navigable and closes them without reopening on Back', async () => {
  38. const user = userEvent.setup();
  39. const deepLinked = messageFixture(20, 2, 'Archive', 'Archived message');
  40. const messages = vi.fn(async () => ({ messages: [deepLinked], total: 1, page: 1, pageSize: 25 }));
  41. mockInboxApis([mailboxFixture(1), mailboxFixture(2)], [deepLinked]);
  42. vi.spyOn(api, 'inboundMessages').mockImplementation(messages);
  43. vi.spyOn(api, 'inboundMessage').mockResolvedValue({ message: deepLinked });
  44. const router = createInboxRouter(['/overview', '/inbox/messages/20'], 1);
  45. renderRouter(router);
  46. expect(await screen.findByText('Archived message')).toBeTruthy();
  47. await waitFor(() => {
  48. const params = new URLSearchParams(router.state.location.search);
  49. expect(params.get('mailboxId')).toBe('2');
  50. expect(params.get('folder')).toBe('Archive');
  51. });
  52. await waitFor(() => expect(messages).toHaveBeenCalledWith(expect.objectContaining({ mailboxId: 2, folder: 'Archive' })));
  53. await user.click(screen.getByRole('tab', { name: 'HTML 源码' }));
  54. await waitFor(() => expect(new URLSearchParams(router.state.location.search).get('tab')).toBe('html'));
  55. expect(detailHistoryState(router.state.location.state)).toEqual({
  56. listPath: '/inbox?mailboxId=2&folder=Archive',
  57. depth: 1,
  58. origin: 'direct'
  59. });
  60. await act(async () => {
  61. await router.navigate(-1);
  62. });
  63. expect(router.state.location.pathname).toBe('/inbox/messages/20');
  64. expect(new URLSearchParams(router.state.location.search).has('tab')).toBe(false);
  65. expect(detailHistoryState(router.state.location.state)).toBeNull();
  66. await act(async () => {
  67. await router.navigate(1);
  68. });
  69. expect(new URLSearchParams(router.state.location.search).get('tab')).toBe('html');
  70. expect(detailHistoryState(router.state.location.state)?.origin).toBe('direct');
  71. fireEvent.click(screen.getByRole('button', { name: 'Close' }));
  72. await waitFor(() => expect(router.state.location.pathname).toBe('/inbox'));
  73. const params = new URLSearchParams(router.state.location.search);
  74. expect(params.get('mailboxId')).toBe('2');
  75. expect(params.get('folder')).toBe('Archive');
  76. await act(async () => {
  77. await router.navigate(-1);
  78. });
  79. expect(router.state.location.pathname).toBe('/overview');
  80. expect(router.state.location.pathname).not.toContain('/messages/');
  81. });
  82. it('uses a detail drawer below the 1280px product breakpoint', async () => {
  83. vi.spyOn(window, 'matchMedia').mockImplementation((query) => mediaQueryList(query === '(min-width: 992px)', query));
  84. const deepLinked = messageFixture(30, 1, 'INBOX', 'Compact detail');
  85. mockInboxApis([mailboxFixture(1)], [deepLinked]);
  86. vi.spyOn(api, 'inboundMessage').mockResolvedValue({ message: deepLinked });
  87. const router = createInboxRouter(['/inbox/messages/30'], 0);
  88. renderRouter(router);
  89. expect(await screen.findByRole('button', { name: 'Close' })).toBeTruthy();
  90. });
  91. });
  92. describe('Inbox request and mailbox behavior', () => {
  93. afterEach(() => vi.restoreAllMocks());
  94. it('keeps the search draft synchronized with browser history', async () => {
  95. mockInboxApis([mailboxFixture(1)], []);
  96. const router = createInboxRouter([
  97. '/inbox?mailboxId=1&folder=INBOX&q=first%20query',
  98. '/inbox?mailboxId=1&folder=INBOX&q=second%20query'
  99. ], 1);
  100. renderRouter(router);
  101. const searchInput = await screen.findByPlaceholderText('搜索发件人、主题或正文预览') as HTMLInputElement;
  102. expect(searchInput.value).toBe('second query');
  103. await act(async () => {
  104. await router.navigate(-1);
  105. });
  106. await waitFor(() => expect(searchInput.value).toBe('first query'));
  107. await act(async () => {
  108. await router.navigate(1);
  109. });
  110. await waitFor(() => expect(searchInput.value).toBe('second query'));
  111. });
  112. it('does not let an older message-list response replace the current mailbox', async () => {
  113. const first = messageFixture(41, 1, 'INBOX', 'Stale mailbox message');
  114. const second = messageFixture(42, 2, 'INBOX', 'Current mailbox message');
  115. let resolveFirst: ((value: { messages: InboundMessage[]; total: number; page: number; pageSize: number }) => void) | undefined;
  116. const firstResponse = new Promise<{ messages: InboundMessage[]; total: number; page: number; pageSize: number }>((resolve) => {
  117. resolveFirst = resolve;
  118. });
  119. mockInboxApis([mailboxFixture(1), mailboxFixture(2)], []);
  120. const list = vi.spyOn(api, 'inboundMessages').mockImplementation(async (filters) => {
  121. const mailboxId = typeof filters === 'number' ? filters : filters?.mailboxId;
  122. if (mailboxId === 1) return firstResponse;
  123. return { messages: [second], total: 1, page: 1, pageSize: 25 };
  124. });
  125. const router = createInboxRouter(['/inbox?mailboxId=1&folder=INBOX'], 0);
  126. renderRouter(router);
  127. await waitFor(() => expect(list).toHaveBeenCalledWith(expect.objectContaining({ mailboxId: 1 })));
  128. await act(async () => {
  129. await router.navigate('/inbox?mailboxId=2&folder=INBOX');
  130. });
  131. expect(await screen.findByText('Current mailbox message')).toBeTruthy();
  132. await act(async () => {
  133. resolveFirst?.({ messages: [first], total: 1, page: 1, pageSize: 25 });
  134. await Promise.resolve();
  135. });
  136. expect(screen.queryByText('Stale mailbox message')).toBeNull();
  137. expect(screen.getByText('Current mailbox message')).toBeTruthy();
  138. });
  139. it('keeps message content visible when marking it as read fails', async () => {
  140. const unread = { ...messageFixture(50, 1, 'INBOX', 'Unread detail'), read: false };
  141. mockInboxApis([mailboxFixture(1, { unreadCount: 1 })], [unread]);
  142. vi.spyOn(api, 'inboundMessage').mockResolvedValue({ message: unread });
  143. vi.spyOn(api, 'markInboundMessageRead').mockRejectedValue(new Error('mark read failed'));
  144. const router = createInboxRouter(['/inbox/messages/50?mailboxId=1&folder=INBOX'], 0);
  145. renderRouter(router);
  146. expect(await screen.findByText('Unread detail body')).toBeTruthy();
  147. expect(await screen.findByText('mark read failed')).toBeTruthy();
  148. });
  149. it('shows unavailable folder counts and retries instead of displaying fake zeroes', async () => {
  150. vi.spyOn(window, 'matchMedia').mockImplementation((query) => mediaQueryList(query === '(min-width: 992px)' || query === '(min-width: 768px)', query));
  151. mockInboxApis([mailboxFixture(1)], []);
  152. const folders = vi.spyOn(api, 'inboundFolders')
  153. .mockRejectedValueOnce(new Error('folder request failed'))
  154. .mockResolvedValue({ folders: [{ name: 'INBOX', specialUse: null, messageCount: 3, unreadCount: 2 }] });
  155. const router = createInboxRouter(['/inbox?mailboxId=1&folder=INBOX'], 0);
  156. renderRouter(router);
  157. const warning = await screen.findByText('文件夹计数暂不可用。');
  158. expect(warning).toBeTruthy();
  159. expect(screen.getAllByLabelText('计数不可用').length).toBeGreaterThan(0);
  160. const alert = warning.closest('.ant-alert');
  161. expect(alert).toBeTruthy();
  162. await userEvent.click(within(alert as HTMLElement).getByRole('button', { name: /刷\s*新/ }));
  163. await waitFor(() => expect(folders).toHaveBeenCalledTimes(2));
  164. await waitFor(() => expect(screen.queryByText('文件夹计数暂不可用。')).toBeNull());
  165. });
  166. it('selects the mailbox with the most recent activity when the URL has no mailbox', async () => {
  167. const older = mailboxFixture(1, { lastMessageAt: '2026-07-14T00:00:00.000Z' });
  168. const recent = mailboxFixture(2, { lastMessageAt: '2026-07-15T00:00:00.000Z' });
  169. mockInboxApis([older, recent], []);
  170. const list = vi.spyOn(api, 'inboundMessages');
  171. const router = createInboxRouter(['/inbox'], 0);
  172. renderRouter(router);
  173. await waitFor(() => expect(list).toHaveBeenCalledWith(expect.objectContaining({ mailboxId: 2 })));
  174. expect(new URLSearchParams(router.state.location.search).get('mailboxId')).toBe('2');
  175. });
  176. it('updates mailbox settings from the routing workspace edit drawer', async () => {
  177. const user = userEvent.setup();
  178. const mailbox = mailboxFixture(1);
  179. mockInboxApis([mailbox], [], [domainFixture(1)]);
  180. const update = vi.spyOn(api, 'updateInboundMailbox').mockResolvedValue({
  181. mailbox: { ...mailbox, displayName: 'Updated inbox', aliases: ['sales'] }
  182. });
  183. const router = createInboxRouter(['/inbox?workspace=routing'], 0);
  184. renderRouter(router);
  185. const mailboxTitle = await screen.findByText(mailbox.address);
  186. const card = mailboxTitle.closest('.ant-card');
  187. expect(card).toBeTruthy();
  188. await user.click(within(card as HTMLElement).getByRole('button', { name: /修改/ }));
  189. const displayName = await screen.findByLabelText('显示名称');
  190. await user.clear(displayName);
  191. await user.type(displayName, 'Updated inbox');
  192. await user.type(screen.getByLabelText('新密码'), 'new-password-123');
  193. await user.clear(screen.getByLabelText('别名'));
  194. await user.type(screen.getByLabelText('别名'), 'sales');
  195. await user.click(screen.getByRole('button', { name: /保\s*存/ }));
  196. await waitFor(() => expect(update).toHaveBeenCalledWith(1, expect.objectContaining({
  197. displayName: 'Updated inbox',
  198. password: 'new-password-123',
  199. aliases: 'sales',
  200. status: 'active'
  201. })));
  202. });
  203. });
  204. function mediaQueryList(matches: boolean, media: string): MediaQueryList {
  205. return {
  206. matches,
  207. media,
  208. onchange: null,
  209. addListener: () => undefined,
  210. removeListener: () => undefined,
  211. addEventListener: () => undefined,
  212. removeEventListener: () => undefined,
  213. dispatchEvent: () => false
  214. };
  215. }
  216. function createInboxRouter(initialEntries: string[], initialIndex: number) {
  217. return createMemoryRouter([
  218. { path: '/inbox', element: <Inbox /> },
  219. { path: '/inbox/messages/:messageId', element: <Inbox /> },
  220. { path: '*', element: <div>other</div> }
  221. ], { initialEntries, initialIndex });
  222. }
  223. function renderRouter(router: ReturnType<typeof createInboxRouter>) {
  224. return render(
  225. <ConfigProvider theme={{ ...mailhubTheme, token: { ...mailhubTheme.token, motion: false } }}>
  226. <AntApp>
  227. <I18nProvider>
  228. <AppContext.Provider value={appContext}>
  229. <RouterProvider router={router} />
  230. </AppContext.Provider>
  231. </I18nProvider>
  232. </AntApp>
  233. </ConfigProvider>
  234. );
  235. }
  236. function mockInboxApis(mailboxes: InboundMailbox[], messages: InboundMessage[], domains: Domain[] = []) {
  237. vi.spyOn(api, 'domains').mockResolvedValue({ domains });
  238. vi.spyOn(api, 'inboundMailboxes').mockResolvedValue({ mailboxes });
  239. vi.spyOn(api, 'inboundFolders').mockImplementation(async (mailboxId) => ({
  240. folders: [
  241. { name: 'INBOX', specialUse: null, messageCount: 0, unreadCount: 0 },
  242. { name: 'Sent', specialUse: '\\Sent', messageCount: mailboxId === 1 ? messages.length : 0, unreadCount: 0 },
  243. { name: 'Archive', specialUse: '\\Archive', messageCount: mailboxId === 2 ? messages.length : 0, unreadCount: 0 }
  244. ]
  245. }));
  246. vi.spyOn(api, 'inboundMessages').mockResolvedValue({ messages, total: messages.length, page: 1, pageSize: 25 });
  247. }
  248. function domainFixture(id: number): Domain {
  249. return {
  250. id,
  251. userId: 1,
  252. dnsCredentialId: null,
  253. smtpRelayId: null,
  254. domain: `example-${id}.test`,
  255. selector: 'mail',
  256. verificationToken: 'verification',
  257. dkimPublic: 'public-key',
  258. senderHost: `mail.example-${id}.test`,
  259. sendingIp: '192.0.2.10',
  260. spfExtra: '',
  261. dmarcPolicy: 'none',
  262. dmarcRua: '',
  263. catchAllAddress: '',
  264. status: {},
  265. createdAt: '2026-07-14T00:00:00.000Z',
  266. updatedAt: '2026-07-14T00:00:00.000Z'
  267. };
  268. }
  269. function mailboxFixture(id: number, overrides: Partial<InboundMailbox> = {}): InboundMailbox {
  270. return {
  271. id,
  272. userId: 1,
  273. domainId: id,
  274. domain: `example-${id}.test`,
  275. address: `inbox-${id}@example-${id}.test`,
  276. localPart: `inbox-${id}`,
  277. displayName: `Inbox ${id}`,
  278. aliases: [],
  279. forwardTo: [],
  280. keepForwarded: true,
  281. quotaMb: 1024,
  282. passwordSet: true,
  283. passwordRecoverable: false,
  284. status: 'active',
  285. messageCount: 2,
  286. unreadCount: 0,
  287. createdAt: '2026-07-14T00:00:00.000Z',
  288. updatedAt: '2026-07-14T00:00:00.000Z',
  289. ...overrides
  290. };
  291. }
  292. function messageFixture(id: number, mailboxId: number, folder: string, subject: string): InboundMessage {
  293. return {
  294. id,
  295. mailboxId,
  296. userId: 1,
  297. domainId: mailboxId,
  298. domain: `example-${mailboxId}.test`,
  299. mailboxAddress: `inbox-${mailboxId}@example-${mailboxId}.test`,
  300. folder,
  301. sender: 'sender@example.test',
  302. recipients: [`inbox-${mailboxId}@example-${mailboxId}.test`],
  303. subject,
  304. messageId: `<message-${id}@example.test>`,
  305. preview: `${subject} preview`,
  306. read: true,
  307. receivedAt: '2026-07-14T00:00:00.000Z',
  308. createdAt: '2026-07-14T00:00:00.000Z',
  309. updatedAt: '2026-07-14T00:00:00.000Z',
  310. textBody: `${subject} body`,
  311. htmlBody: `<p>${subject}</p>`,
  312. rawMessage: `Subject: ${subject}`
  313. };
  314. }
  315. const runtimeConfig: RuntimeConfig = {
  316. appBaseUrl: 'https://mail.example.test',
  317. mailHostname: 'mail.example.test',
  318. sendingIp: '192.0.2.10',
  319. defaultSpfMechanisms: '',
  320. dmarcPolicy: 'none',
  321. dmarcRua: '',
  322. sendRequiresVerified: true,
  323. engagementTrackingEnabled: true,
  324. listUnsubscribeMailto: '',
  325. listUnsubscribeUrl: '',
  326. listUnsubscribePostEnabled: false,
  327. feedbackIdEnabled: false,
  328. reportAbuseTo: '',
  329. csaComplaintsTo: '',
  330. bounceAddress: '',
  331. bounceEnvelopeEnabled: false
  332. };
  333. const appContext: AppContextValue = {
  334. user: { id: 1, username: 'admin', email: 'admin@example.test', role: 'admin', status: 'active' },
  335. config: runtimeConfig,
  336. refreshBootstrap: vi.fn(async () => undefined),
  337. logout: vi.fn(async () => undefined)
  338. };