inbox-navigation.test.tsx 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import { App as AntApp, ConfigProvider } from 'antd';
  2. import { act, fireEvent, render, screen, waitFor } 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 { 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 1024px 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. function mediaQueryList(matches: boolean, media: string): MediaQueryList {
  93. return {
  94. matches,
  95. media,
  96. onchange: null,
  97. addListener: () => undefined,
  98. removeListener: () => undefined,
  99. addEventListener: () => undefined,
  100. removeEventListener: () => undefined,
  101. dispatchEvent: () => false
  102. };
  103. }
  104. function createInboxRouter(initialEntries: string[], initialIndex: number) {
  105. return createMemoryRouter([
  106. { path: '/inbox', element: <Inbox /> },
  107. { path: '/inbox/messages/:messageId', element: <Inbox /> },
  108. { path: '*', element: <div>other</div> }
  109. ], { initialEntries, initialIndex });
  110. }
  111. function renderRouter(router: ReturnType<typeof createInboxRouter>) {
  112. return render(
  113. <ConfigProvider theme={{ ...mailhubTheme, token: { ...mailhubTheme.token, motion: false } }}>
  114. <AntApp>
  115. <I18nProvider>
  116. <AppContext.Provider value={appContext}>
  117. <RouterProvider router={router} />
  118. </AppContext.Provider>
  119. </I18nProvider>
  120. </AntApp>
  121. </ConfigProvider>
  122. );
  123. }
  124. function mockInboxApis(mailboxes: InboundMailbox[], messages: InboundMessage[]) {
  125. vi.spyOn(api, 'domains').mockResolvedValue({ domains: [] });
  126. vi.spyOn(api, 'inboundMailboxes').mockResolvedValue({ mailboxes });
  127. vi.spyOn(api, 'inboundFolders').mockImplementation(async (mailboxId) => ({
  128. folders: [
  129. { name: 'INBOX', specialUse: null, messageCount: 0, unreadCount: 0 },
  130. { name: 'Sent', specialUse: '\\Sent', messageCount: mailboxId === 1 ? messages.length : 0, unreadCount: 0 },
  131. { name: 'Archive', specialUse: '\\Archive', messageCount: mailboxId === 2 ? messages.length : 0, unreadCount: 0 }
  132. ]
  133. }));
  134. vi.spyOn(api, 'inboundMessages').mockResolvedValue({ messages, total: messages.length, page: 1, pageSize: 25 });
  135. }
  136. function mailboxFixture(id: number): InboundMailbox {
  137. return {
  138. id,
  139. userId: 1,
  140. domainId: id,
  141. domain: `example-${id}.test`,
  142. address: `inbox-${id}@example-${id}.test`,
  143. localPart: `inbox-${id}`,
  144. displayName: `Inbox ${id}`,
  145. aliases: [],
  146. forwardTo: [],
  147. keepForwarded: true,
  148. quotaMb: 1024,
  149. passwordSet: true,
  150. passwordRecoverable: false,
  151. status: 'active',
  152. messageCount: 2,
  153. unreadCount: 0,
  154. createdAt: '2026-07-14T00:00:00.000Z',
  155. updatedAt: '2026-07-14T00:00:00.000Z'
  156. };
  157. }
  158. function messageFixture(id: number, mailboxId: number, folder: string, subject: string): InboundMessage {
  159. return {
  160. id,
  161. mailboxId,
  162. userId: 1,
  163. domainId: mailboxId,
  164. domain: `example-${mailboxId}.test`,
  165. mailboxAddress: `inbox-${mailboxId}@example-${mailboxId}.test`,
  166. folder,
  167. sender: 'sender@example.test',
  168. recipients: [`inbox-${mailboxId}@example-${mailboxId}.test`],
  169. subject,
  170. messageId: `<message-${id}@example.test>`,
  171. preview: `${subject} preview`,
  172. read: true,
  173. receivedAt: '2026-07-14T00:00:00.000Z',
  174. createdAt: '2026-07-14T00:00:00.000Z',
  175. updatedAt: '2026-07-14T00:00:00.000Z',
  176. textBody: `${subject} body`,
  177. htmlBody: `<p>${subject}</p>`,
  178. rawMessage: `Subject: ${subject}`
  179. };
  180. }
  181. const runtimeConfig: RuntimeConfig = {
  182. appBaseUrl: 'https://mail.example.test',
  183. mailHostname: 'mail.example.test',
  184. sendingIp: '192.0.2.10',
  185. defaultSpfMechanisms: '',
  186. dmarcPolicy: 'none',
  187. dmarcRua: '',
  188. sendRequiresVerified: true,
  189. engagementTrackingEnabled: true,
  190. listUnsubscribeMailto: '',
  191. listUnsubscribeUrl: '',
  192. listUnsubscribePostEnabled: false,
  193. feedbackIdEnabled: false,
  194. reportAbuseTo: '',
  195. csaComplaintsTo: '',
  196. bounceAddress: '',
  197. bounceEnvelopeEnabled: false
  198. };
  199. const appContext: AppContextValue = {
  200. user: { id: 1, username: 'admin', email: 'admin@example.test', role: 'admin', status: 'active' },
  201. config: runtimeConfig,
  202. refreshBootstrap: vi.fn(async () => undefined),
  203. logout: vi.fn(async () => undefined)
  204. };