domains-workflow.test.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import { App as AntApp, ConfigProvider } from 'antd';
  2. import { cleanup, render, screen, waitFor, within } from '@testing-library/react';
  3. import userEvent from '@testing-library/user-event';
  4. import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
  5. import { afterEach, describe, expect, it, vi } from 'vitest';
  6. import { AppContext } from '../../src/frontend/app-context';
  7. import { I18nProvider } from '../../src/frontend/i18n/react';
  8. import { api } from '../../src/frontend/services/api';
  9. import { mailhubTheme } from '../../src/frontend/theme';
  10. import type { AppContextValue } from '../../src/frontend/app-context';
  11. import type { AddDomainPayload, Domain } from '../../src/frontend/types';
  12. import Domains, { createDomainWithSetup, readDomainPagination } from '../../src/pages/Domains';
  13. import DomainDetail from '../../src/pages/Domains/DomainDetail';
  14. const defaultMatchMedia = window.matchMedia;
  15. afterEach(() => {
  16. Object.defineProperty(window, 'matchMedia', { configurable: true, writable: true, value: defaultMatchMedia });
  17. });
  18. describe('Domains URL state and creation workflow', () => {
  19. it('normalizes unsupported pagination values', () => {
  20. expect(readDomainPagination(new URLSearchParams('page=-1&pageSize=999'))).toEqual({ page: 1, pageSize: 20 });
  21. });
  22. it('opens from create=1 and removes only the create flag when cancelled', async () => {
  23. const user = userEvent.setup();
  24. mockListApis(makeDomains(25));
  25. renderPage('/domains?create=1&q=keep');
  26. expect(await screen.findByText('添加发信域名')).toBeTruthy();
  27. await waitFor(() => {
  28. const params = currentSearchParams();
  29. expect(params.get('page')).toBe('1');
  30. expect(params.get('pageSize')).toBe('20');
  31. });
  32. const drawer = screen.getByRole('dialog', { name: '添加发信域名' });
  33. await user.click(within(drawer).getByRole('button', { name: /取\s*消/ }));
  34. await waitFor(() => expect(currentSearchParams().has('create')).toBe(false));
  35. const params = currentSearchParams();
  36. expect(params.get('q')).toBe('keep');
  37. expect(params.get('page')).toBe('1');
  38. expect(params.get('pageSize')).toBe('20');
  39. });
  40. it('always applies DNS after an automatic-mode creation', async () => {
  41. const created = makeDomain(1);
  42. const applied = { ...created, status: { ...created.status, verified: true } };
  43. const operations = {
  44. createDomain: vi.fn(async () => ({ domain: created })),
  45. applyDns: vi.fn(async () => ({ domain: applied, apply: { ok: true, results: [] } })),
  46. checkDomain: vi.fn(async () => ({ domain: created }))
  47. };
  48. const result = await createDomainWithSetup({ ...createPayload, dnsCredentialId: 9 }, operations);
  49. expect(operations.applyDns).toHaveBeenCalledWith(created.id);
  50. expect(operations.checkDomain).not.toHaveBeenCalled();
  51. expect(result).toMatchObject({ domain: applied, setup: 'complete', followUp: 'apply' });
  52. });
  53. it('checks DNS after a manual creation only when immediate checking is enabled', async () => {
  54. const created = makeDomain(1);
  55. const checked = { ...created, status: { ...created.status, checkedAt: '2026-07-14T01:00:00.000Z' } };
  56. const operations = {
  57. createDomain: vi.fn(async () => ({ domain: created })),
  58. applyDns: vi.fn(async () => ({ domain: created, apply: { ok: true, results: [] } })),
  59. checkDomain: vi.fn(async () => ({ domain: checked }))
  60. };
  61. const result = await createDomainWithSetup({ ...createPayload, immediateCheck: true }, operations);
  62. expect(operations.checkDomain).toHaveBeenCalledWith(created.id);
  63. expect(operations.applyDns).not.toHaveBeenCalled();
  64. expect(result).toMatchObject({ domain: checked, setup: 'complete', followUp: 'check' });
  65. });
  66. it('returns partial after a follow-up failure without turning it into a second create failure', async () => {
  67. const created = makeDomain(1);
  68. const operations = {
  69. createDomain: vi.fn(async () => ({ domain: created })),
  70. applyDns: vi.fn(async () => { throw new Error('provider unavailable'); }),
  71. checkDomain: vi.fn(async () => ({ domain: created }))
  72. };
  73. await expect(createDomainWithSetup({ ...createPayload, dnsCredentialId: 9 }, operations)).resolves.toMatchObject({
  74. domain: created,
  75. setup: 'partial',
  76. followUp: 'apply',
  77. error: 'provider unavailable'
  78. });
  79. expect(operations.createDomain).toHaveBeenCalledTimes(1);
  80. });
  81. it('treats apply.ok=false as partial and keeps the persisted per-record result', async () => {
  82. const created = makeDomain(1);
  83. const applied = {
  84. ...created,
  85. status: {
  86. ...created.status,
  87. apply: {
  88. ok: false,
  89. results: [{ key: 'dmarc', type: 'TXT', host: '_dmarc.example.test', ok: false, error: 'permission denied' }]
  90. }
  91. }
  92. } satisfies Domain;
  93. const operations = {
  94. createDomain: vi.fn(async () => ({ domain: created })),
  95. applyDns: vi.fn(async () => ({ domain: applied, apply: applied.status.apply })),
  96. checkDomain: vi.fn(async () => ({ domain: created }))
  97. };
  98. await expect(createDomainWithSetup({ ...createPayload, dnsCredentialId: 9 }, operations)).resolves.toMatchObject({
  99. domain: applied,
  100. setup: 'partial',
  101. followUp: 'apply',
  102. error: 'permission denied'
  103. });
  104. });
  105. it('still rejects when domain creation itself fails', async () => {
  106. const operations = {
  107. createDomain: vi.fn(async () => { throw new Error('domain already exists'); }),
  108. applyDns: vi.fn(async () => ({ domain: makeDomain(1), apply: { ok: true, results: [] } })),
  109. checkDomain: vi.fn(async () => ({ domain: makeDomain(1) }))
  110. };
  111. await expect(createDomainWithSetup({ ...createPayload, dnsCredentialId: 9 }, operations)).rejects.toThrow('domain already exists');
  112. expect(operations.applyDns).not.toHaveBeenCalled();
  113. expect(operations.checkDomain).not.toHaveBeenCalled();
  114. });
  115. it('keeps page and pageSize in the URL and resets page when a filter changes', async () => {
  116. const user = userEvent.setup();
  117. mockListApis(makeDomains(25));
  118. setViewport(390);
  119. renderPage('/domains?page=2&pageSize=10');
  120. expect(await screen.findByText('keep-11.example.test')).toBeTruthy();
  121. expect(screen.queryByText('keep-01.example.test')).toBeNull();
  122. await user.type(screen.getByLabelText('搜索域名'), '01');
  123. await waitFor(() => {
  124. const params = currentSearchParams();
  125. expect(params.get('q')).toBe('01');
  126. expect(params.get('page')).toBe('1');
  127. expect(params.get('pageSize')).toBe('10');
  128. });
  129. expect(await screen.findByText('keep-01.example.test')).toBeTruthy();
  130. });
  131. it('keeps the domain list usable when supporting integrations fail', async () => {
  132. const domain = { ...makeDomain(1), dnsCredentialId: 8 };
  133. vi.spyOn(api, 'domains').mockResolvedValue({ domains: [domain] });
  134. vi.spyOn(api, 'dnsCredentials').mockRejectedValue(new Error('DNS provider unavailable'));
  135. vi.spyOn(api, 'smtpRelays').mockResolvedValue({ relays: [] });
  136. vi.spyOn(api, 'events').mockRejectedValue(new Error('Activity service unavailable'));
  137. renderPage('/domains');
  138. expect(await screen.findByText(domain.domain)).toBeTruthy();
  139. expect(screen.getByText('部分辅助信息暂不可用')).toBeTruthy();
  140. expect(screen.getByText(/DNS provider unavailable/)).toBeTruthy();
  141. expect(screen.getAllByText('暂不可用').length).toBeGreaterThan(0);
  142. expect(screen.queryByText('域名列表加载失败')).toBeNull();
  143. });
  144. it('keeps stale domains visible but reports a primary-list refresh failure', async () => {
  145. const user = userEvent.setup();
  146. const domain = makeDomain(1);
  147. vi.spyOn(api, 'domains')
  148. .mockResolvedValueOnce({ domains: [domain] })
  149. .mockRejectedValueOnce(new Error('Domain service unavailable'));
  150. vi.spyOn(api, 'dnsCredentials')
  151. .mockRejectedValueOnce(new Error('DNS provider unavailable'))
  152. .mockResolvedValue({ credentials: [] });
  153. vi.spyOn(api, 'smtpRelays').mockResolvedValue({ relays: [] });
  154. vi.spyOn(api, 'events').mockResolvedValue({ events: [], total: 0, page: 1, pageSize: 100 });
  155. renderPage('/domains');
  156. expect(await screen.findByText(domain.domain)).toBeTruthy();
  157. const auxiliaryWarning = screen.getByText('部分辅助信息暂不可用').closest('.ant-alert');
  158. expect(auxiliaryWarning).not.toBeNull();
  159. await user.click(within(auxiliaryWarning as HTMLElement).getByRole('button', { name: '重试' }));
  160. const primaryError = await screen.findByText('域名列表加载失败');
  161. const primaryAlert = primaryError.closest('.ant-alert');
  162. expect(primaryAlert).not.toBeNull();
  163. expect(within(primaryAlert as HTMLElement).getByText('Domain service unavailable')).toBeTruthy();
  164. expect(screen.getByText(domain.domain)).toBeTruthy();
  165. });
  166. it('uses the same URL page slice on mobile and desktop', async () => {
  167. const domains = makeDomains(25);
  168. const expected = domains.slice(10, 20).map((domain) => domain.domain);
  169. mockListApis(domains);
  170. setViewport(390);
  171. renderPage('/domains?page=2&pageSize=10');
  172. await screen.findByText(expected[0]);
  173. const mobile = visibleDomainNames(domains);
  174. cleanup();
  175. setViewport(1024);
  176. renderPage('/domains?page=2&pageSize=10');
  177. await screen.findByText(expected[0]);
  178. const desktop = visibleDomainNames(domains);
  179. expect(mobile).toEqual(expected);
  180. expect(desktop).toEqual(expected);
  181. });
  182. it('shows partial setup guidance and each persisted DNS apply result', async () => {
  183. const domain = {
  184. ...makeDomain(7),
  185. dnsCredentialId: 4,
  186. status: {
  187. verified: false,
  188. records: [],
  189. apply: {
  190. ok: false,
  191. results: [
  192. { key: 'spf', type: 'TXT', host: 'example.test', ok: true, detail: 'updated' },
  193. { key: 'dmarc', type: 'TXT', host: '_dmarc.example.test', ok: false, error: 'permission denied' }
  194. ]
  195. }
  196. }
  197. } satisfies Domain;
  198. mockListApis([domain], [{ id: 4, userId: 1, name: 'Cloudflare', provider: 'cloudflare', zoneName: 'example.test', defaultTtl: 600, createdAt: domain.createdAt, updatedAt: domain.updatedAt }]);
  199. renderPage('/domains/7/dns?setup=partial');
  200. expect(await screen.findByText('域名已创建,但 DNS 后续操作需要处理')).toBeTruthy();
  201. const title = await screen.findByText('DNS 写入结果');
  202. const card = title.closest('.ant-card');
  203. expect(card).not.toBeNull();
  204. expect(within(card as HTMLElement).getByText('example.test')).toBeTruthy();
  205. expect(within(card as HTMLElement).getByText('_dmarc.example.test')).toBeTruthy();
  206. expect(within(card as HTMLElement).getByText('permission denied')).toBeTruthy();
  207. expect(within(card as HTMLElement).getByText('成功')).toBeTruthy();
  208. expect(within(card as HTMLElement).getByText('失败')).toBeTruthy();
  209. });
  210. });
  211. function renderPage(initialEntry: string) {
  212. return render(
  213. <ConfigProvider theme={mailhubTheme}>
  214. <AntApp>
  215. <I18nProvider>
  216. <AppContext.Provider value={context}>
  217. <MemoryRouter initialEntries={[initialEntry]}>
  218. <Routes>
  219. <Route path="/domains" element={<><Domains /><LocationProbe /></>} />
  220. <Route path="/domains/:id/:section" element={<><DomainDetail /><LocationProbe /></>} />
  221. </Routes>
  222. </MemoryRouter>
  223. </AppContext.Provider>
  224. </I18nProvider>
  225. </AntApp>
  226. </ConfigProvider>
  227. );
  228. }
  229. function LocationProbe() {
  230. const location = useLocation();
  231. return <output data-testid="location-search">{location.search}</output>;
  232. }
  233. function currentSearchParams() {
  234. return new URLSearchParams(screen.getByTestId('location-search').textContent || '');
  235. }
  236. function mockListApis(domains: Domain[], credentials: Awaited<ReturnType<typeof api.dnsCredentials>>['credentials'] = []) {
  237. vi.spyOn(api, 'domains').mockResolvedValue({ domains });
  238. vi.spyOn(api, 'dnsCredentials').mockResolvedValue({ credentials });
  239. vi.spyOn(api, 'smtpRelays').mockResolvedValue({ relays: [] });
  240. vi.spyOn(api, 'events').mockResolvedValue({ events: [], total: 0, page: 1, pageSize: 100 });
  241. }
  242. function setViewport(width: number) {
  243. Object.defineProperty(window, 'matchMedia', {
  244. configurable: true,
  245. writable: true,
  246. value: (query: string) => {
  247. const min = Number(query.match(/min-width:\s*(\d+)px/)?.[1] || 0);
  248. const max = Number(query.match(/max-width:\s*(\d+)px/)?.[1] || Number.POSITIVE_INFINITY);
  249. return {
  250. matches: width >= min && width <= max,
  251. media: query,
  252. onchange: null,
  253. addListener: () => undefined,
  254. removeListener: () => undefined,
  255. addEventListener: () => undefined,
  256. removeEventListener: () => undefined,
  257. dispatchEvent: () => false
  258. };
  259. }
  260. });
  261. }
  262. function visibleDomainNames(domains: Domain[]) {
  263. return domains.filter((domain) => screen.queryAllByText(domain.domain).length > 0).map((domain) => domain.domain);
  264. }
  265. function makeDomains(count: number) {
  266. return Array.from({ length: count }, (_, index) => makeDomain(index + 1));
  267. }
  268. function makeDomain(id: number): Domain {
  269. const ordinal = String(id).padStart(2, '0');
  270. return {
  271. id,
  272. userId: 1,
  273. dnsCredentialId: null,
  274. smtpRelayId: null,
  275. domain: `keep-${ordinal}.example.test`,
  276. selector: 'mh202607',
  277. verificationToken: `verification-${id}`,
  278. dkimPublic: 'public-key',
  279. senderHost: `mail-${ordinal}.example.test`,
  280. sendingIp: '192.0.2.10',
  281. spfExtra: '',
  282. dmarcPolicy: 'none',
  283. dmarcRua: '',
  284. catchAllAddress: '',
  285. status: { verified: false, records: [] },
  286. createdAt: '2026-07-14T00:00:00.000Z',
  287. updatedAt: '2026-07-14T00:00:00.000Z'
  288. };
  289. }
  290. const createPayload: AddDomainPayload = {
  291. domain: 'example.test',
  292. senderHost: 'mail.example.test',
  293. sendingIp: '192.0.2.10',
  294. selector: 'mh202607',
  295. dmarcPolicy: 'none',
  296. immediateCheck: true
  297. };
  298. const context: AppContextValue = {
  299. user: { id: 1, username: 'operator', email: 'operator@example.test', role: 'admin', status: 'active' },
  300. config: {
  301. appBaseUrl: 'https://mail.example.test',
  302. mailHostname: 'mail.example.test',
  303. sendingIp: '192.0.2.10',
  304. defaultSpfMechanisms: '',
  305. dmarcPolicy: 'none',
  306. dmarcRua: '',
  307. sendRequiresVerified: true,
  308. engagementTrackingEnabled: true,
  309. listUnsubscribeMailto: '',
  310. listUnsubscribeUrl: '',
  311. listUnsubscribePostEnabled: false,
  312. feedbackIdEnabled: false,
  313. reportAbuseTo: '',
  314. csaComplaintsTo: '',
  315. bounceAddress: '',
  316. bounceEnvelopeEnabled: false
  317. },
  318. refreshBootstrap: vi.fn(async () => undefined),
  319. logout: vi.fn(async () => undefined)
  320. };