domains-workflow.test.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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('uses the same URL page slice on mobile and desktop', async () => {
  132. const domains = makeDomains(25);
  133. const expected = domains.slice(10, 20).map((domain) => domain.domain);
  134. mockListApis(domains);
  135. setViewport(390);
  136. renderPage('/domains?page=2&pageSize=10');
  137. await screen.findByText(expected[0]);
  138. const mobile = visibleDomainNames(domains);
  139. cleanup();
  140. setViewport(1024);
  141. renderPage('/domains?page=2&pageSize=10');
  142. await screen.findByText(expected[0]);
  143. const desktop = visibleDomainNames(domains);
  144. expect(mobile).toEqual(expected);
  145. expect(desktop).toEqual(expected);
  146. });
  147. it('shows partial setup guidance and each persisted DNS apply result', async () => {
  148. const domain = {
  149. ...makeDomain(7),
  150. dnsCredentialId: 4,
  151. status: {
  152. verified: false,
  153. records: [],
  154. apply: {
  155. ok: false,
  156. results: [
  157. { key: 'spf', type: 'TXT', host: 'example.test', ok: true, detail: 'updated' },
  158. { key: 'dmarc', type: 'TXT', host: '_dmarc.example.test', ok: false, error: 'permission denied' }
  159. ]
  160. }
  161. }
  162. } satisfies Domain;
  163. mockListApis([domain], [{ id: 4, userId: 1, name: 'Cloudflare', provider: 'cloudflare', zoneName: 'example.test', defaultTtl: 600, createdAt: domain.createdAt, updatedAt: domain.updatedAt }]);
  164. renderPage('/domains/7/dns?setup=partial');
  165. expect(await screen.findByText('域名已创建,但 DNS 后续操作需要处理')).toBeTruthy();
  166. const title = await screen.findByText('DNS 写入结果');
  167. const card = title.closest('.ant-card');
  168. expect(card).not.toBeNull();
  169. expect(within(card as HTMLElement).getByText('example.test')).toBeTruthy();
  170. expect(within(card as HTMLElement).getByText('_dmarc.example.test')).toBeTruthy();
  171. expect(within(card as HTMLElement).getByText('permission denied')).toBeTruthy();
  172. expect(within(card as HTMLElement).getByText('成功')).toBeTruthy();
  173. expect(within(card as HTMLElement).getByText('失败')).toBeTruthy();
  174. });
  175. });
  176. function renderPage(initialEntry: string) {
  177. return render(
  178. <ConfigProvider theme={mailhubTheme}>
  179. <AntApp>
  180. <I18nProvider>
  181. <AppContext.Provider value={context}>
  182. <MemoryRouter initialEntries={[initialEntry]}>
  183. <Routes>
  184. <Route path="/domains" element={<><Domains /><LocationProbe /></>} />
  185. <Route path="/domains/:id/:section" element={<><DomainDetail /><LocationProbe /></>} />
  186. </Routes>
  187. </MemoryRouter>
  188. </AppContext.Provider>
  189. </I18nProvider>
  190. </AntApp>
  191. </ConfigProvider>
  192. );
  193. }
  194. function LocationProbe() {
  195. const location = useLocation();
  196. return <output data-testid="location-search">{location.search}</output>;
  197. }
  198. function currentSearchParams() {
  199. return new URLSearchParams(screen.getByTestId('location-search').textContent || '');
  200. }
  201. function mockListApis(domains: Domain[], credentials: Awaited<ReturnType<typeof api.dnsCredentials>>['credentials'] = []) {
  202. vi.spyOn(api, 'domains').mockResolvedValue({ domains });
  203. vi.spyOn(api, 'dnsCredentials').mockResolvedValue({ credentials });
  204. vi.spyOn(api, 'smtpRelays').mockResolvedValue({ relays: [] });
  205. vi.spyOn(api, 'events').mockResolvedValue({ events: [], total: 0, page: 1, pageSize: 100 });
  206. }
  207. function setViewport(width: number) {
  208. Object.defineProperty(window, 'matchMedia', {
  209. configurable: true,
  210. writable: true,
  211. value: (query: string) => {
  212. const min = Number(query.match(/min-width:\s*(\d+)px/)?.[1] || 0);
  213. const max = Number(query.match(/max-width:\s*(\d+)px/)?.[1] || Number.POSITIVE_INFINITY);
  214. return {
  215. matches: width >= min && width <= max,
  216. media: query,
  217. onchange: null,
  218. addListener: () => undefined,
  219. removeListener: () => undefined,
  220. addEventListener: () => undefined,
  221. removeEventListener: () => undefined,
  222. dispatchEvent: () => false
  223. };
  224. }
  225. });
  226. }
  227. function visibleDomainNames(domains: Domain[]) {
  228. return domains.filter((domain) => screen.queryAllByText(domain.domain).length > 0).map((domain) => domain.domain);
  229. }
  230. function makeDomains(count: number) {
  231. return Array.from({ length: count }, (_, index) => makeDomain(index + 1));
  232. }
  233. function makeDomain(id: number): Domain {
  234. const ordinal = String(id).padStart(2, '0');
  235. return {
  236. id,
  237. userId: 1,
  238. dnsCredentialId: null,
  239. smtpRelayId: null,
  240. domain: `keep-${ordinal}.example.test`,
  241. selector: 'mh202607',
  242. verificationToken: `verification-${id}`,
  243. dkimPublic: 'public-key',
  244. senderHost: `mail-${ordinal}.example.test`,
  245. sendingIp: '192.0.2.10',
  246. spfExtra: '',
  247. dmarcPolicy: 'none',
  248. dmarcRua: '',
  249. catchAllAddress: '',
  250. status: { verified: false, records: [] },
  251. createdAt: '2026-07-14T00:00:00.000Z',
  252. updatedAt: '2026-07-14T00:00:00.000Z'
  253. };
  254. }
  255. const createPayload: AddDomainPayload = {
  256. domain: 'example.test',
  257. senderHost: 'mail.example.test',
  258. sendingIp: '192.0.2.10',
  259. selector: 'mh202607',
  260. dmarcPolicy: 'none',
  261. immediateCheck: true
  262. };
  263. const context: AppContextValue = {
  264. user: { id: 1, username: 'operator', email: 'operator@example.test', role: 'admin', status: 'active' },
  265. config: {
  266. appBaseUrl: 'https://mail.example.test',
  267. mailHostname: 'mail.example.test',
  268. sendingIp: '192.0.2.10',
  269. defaultSpfMechanisms: '',
  270. dmarcPolicy: 'none',
  271. dmarcRua: '',
  272. sendRequiresVerified: true,
  273. engagementTrackingEnabled: true,
  274. listUnsubscribeMailto: '',
  275. listUnsubscribeUrl: '',
  276. listUnsubscribePostEnabled: false,
  277. feedbackIdEnabled: false,
  278. reportAbuseTo: '',
  279. csaComplaintsTo: '',
  280. bounceAddress: '',
  281. bounceEnvelopeEnabled: false
  282. },
  283. refreshBootstrap: vi.fn(async () => undefined),
  284. logout: vi.fn(async () => undefined)
  285. };