/** * 首批组件挂载用例之二(四面9分口径 §2 后管「0 组件挂载测试」)。 * * 靶子是 NotificationBell.vue 的两处静默 catch(未读数轮询、点明细标已读)。 * 这里跑真组件:真 pinia 会话、真 `notification-bell-model` 里的提示闸门、真定时器 * (用 vi 的假时钟推进 60s 轮询),只把两个出口(api 与 admin-feedback-ui)换成可断言的假件 * ⇒ 判的是运行时行为,不是读源码的形状钉子。 * * 10-13 聚合改造(场景 × 自然日 × 主体用户)后,面板默认视图拿的是 `fetchNotificationGroups`, * 明细要展开聚合行才由 `fetchNotificationList` 取 ⇒ 点已读那两支都先展开再点明细行; * 顺带钉住「聚合行点击只展开、不替用户标已读」与「红点按组数、组内没读完不许掉」。 * * ⚠ 面板是 ``:每支用例都必须 unmount 并清空 body, * 否则上一支留下的那一行 `.bell-item--unread` 会被这一支的 document 查询捡到(实测会串味)。 * ⚠ 这面还有一支 `npm run test:mount`(vitest,只收 tests/mount/**), * 与 `npm test`(node --test,glob 不递归)互不抓取 ⇒ 改铃铛必须两把都跑,只跑一把就是没验。 */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { flushPromises, mount, type VueWrapper } from '@vue/test-utils' import { createPinia, setActivePinia, type Pinia } from 'pinia' import NotificationBell from '@/components/NotificationBell.vue' import { useAdminSessionStore } from '@/stores/admin-session' import { NOTIFICATION_POLL_INTERVAL_MS } from '@/layout/notification-bell-model' const feedback = vi.hoisted(() => ({ showAdminFeedback: vi.fn(), runBusy: vi.fn() })) const api = vi.hoisted(() => ({ ADMIN_NOTIFICATION_SEVERITY_LABELS: { urgent: '紧急', high: '高危', medium: '中危', low: '低危' }, fetchNotificationSummary: vi.fn(), fetchNotificationGroups: vi.fn(), fetchNotificationList: vi.fn(), markNotificationRead: vi.fn(), markAllNotificationsRead: vi.fn(), })) vi.mock('@/components/admin-feedback-ui', () => feedback) vi.mock('@/api/notifications', () => api) const notification = (over: Record = {}) => ({ id: 7, scene: 'service_down', level: 'error', title: '品牌检测服务挂了', content: '上游 503', read: false, readAt: null, createdAt: new Date().toISOString(), ...over, }) /** 聚合行:一条组 = 场景 × 自然日 × 主体用户,rowCount 是折叠前的明细条数。 */ const group = (over: Record = {}) => ({ latestId: 7, scene: 'service_down', category: 'system_error', day: '2026-09-13', subjectUserId: 1160, rowCount: 1, unreadCount: 1, level: 'error', title: '品牌检测服务挂了', content: '上游 503', createdAt: new Date().toISOString(), ...over, }) const groupPage = (rows: unknown[], over: Record = {}) => ({ groups: rows, total: rows.length, rowCount: rows.length, page: 1, pageSize: 6, unreadGroupCount: rows.filter((g) => (g as { unreadCount: number }).unreadCount > 0).length, unreadCount: rows.reduce((sum, g) => sum + (g as { unreadCount: number }).unreadCount, 0), ...over, }) describe('NotificationBell:两处失败必须可见', () => { let pinia: Pinia let wrapper: VueWrapper | null = null function mountBell() { wrapper = mount(NotificationBell, { attachTo: document.body, global: { plugins: [pinia] } }) return wrapper } /** 只看当前这一棵树里的面板:Teleport 出去的内容挂在 document.body 上。 */ function panelRow(selector: string): HTMLElement | null { return document.body.querySelector(selector) as HTMLElement | null } /** 展开第一个聚合行(聚合行点击只展开,明细行才是能标已读的那一层)。 */ async function expandFirstGroup() { const row = panelRow('.bell-group') if (!row) throw new Error('面板 Teleport 到 body 后没渲染出聚合行') row.click() await flushPromises() } beforeEach(() => { vi.clearAllMocks() pinia = createPinia() setActivePinia(pinia) useAdminSessionStore().user = { id: 9, username: 'root', role: 'super_admin' } api.fetchNotificationGroups.mockResolvedValue(groupPage([])) api.fetchNotificationList.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 50, unreadCount: 0 }) api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 0, unreadGroupCount: 0, latestId: 0 }) api.markNotificationRead.mockResolvedValue(true) vi.spyOn(console, 'warn').mockImplementation(() => {}) }) afterEach(() => { wrapper?.unmount() wrapper = null document.body.innerHTML = '' vi.useRealTimers() }) it('未读数接口挂了:立刻给一条带原因的 warning,而不是红点无声消失', async () => { api.fetchNotificationSummary.mockRejectedValue(new Error('502 Bad Gateway')) mountBell() await flushPromises() expect(feedback.showAdminFeedback).toHaveBeenCalledTimes(1) expect(feedback.showAdminFeedback.mock.calls[0]).toEqual(['通知未读数刷新失败:502 Bad Gateway', 'warning']) }) it('轮询闸门:同一场故障连打三轮也只提示一次,恢复后再坏一次要再提示', async () => { vi.useFakeTimers() api.fetchNotificationSummary.mockRejectedValue(new Error('500')) mountBell() await vi.advanceTimersByTimeAsync(0) expect(feedback.showAdminFeedback).toHaveBeenCalledTimes(1) await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS * 3) expect(feedback.showAdminFeedback).toHaveBeenCalledTimes(1) api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 11 }) await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS) api.fetchNotificationSummary.mockRejectedValue(new Error('503')) await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS) expect(feedback.showAdminFeedback).toHaveBeenCalledTimes(2) expect(feedback.showAdminFeedback.mock.calls[1][0]).toContain('503') }) it('点通知标已读失败:提示带原因,且这条不许被前端冒充成"已读"', async () => { api.fetchNotificationGroups.mockResolvedValue(groupPage([group({ latestId: 21 })])) api.fetchNotificationList.mockResolvedValue({ items: [notification({ id: 21 })], total: 1, page: 1, pageSize: 50, unreadCount: 1, }) api.markNotificationRead.mockRejectedValue(new Error('403 Forbidden')) const bell = mountBell() await flushPromises() await bell.find('button.bell-trigger').trigger('click') await flushPromises() // 展开这一步本身不许标已读:口径是"聚合行只展开,已读进明细逐条点" expect(api.markNotificationRead).not.toHaveBeenCalled() await expandFirstGroup() const row = panelRow('.bell-item--detail') if (!row) throw new Error('展开聚合行后没渲染出明细行') row.click() await flushPromises() expect(feedback.showAdminFeedback).toHaveBeenCalledWith('这条通知没能标记为已读:403 Forbidden', 'error') // 前端不许替后端宣布已读:行仍是未读态、徽标还在 expect(panelRow('.bell-item--detail')?.className).toContain('bell-item--unread') expect(bell.find('.bell-badge').exists()).toBe(true) }) it('反向钉:标已读成功时一句提示都不许有,行也要真的转为已读', async () => { api.fetchNotificationGroups.mockResolvedValue(groupPage([group({ latestId: 22 })])) api.fetchNotificationList.mockResolvedValue({ items: [notification({ id: 22 })], total: 1, page: 1, pageSize: 50, unreadCount: 1, }) api.markNotificationRead.mockResolvedValue(true) const bell = mountBell() await flushPromises() await bell.find('button.bell-trigger').trigger('click') await flushPromises() await expandFirstGroup() const row = panelRow('.bell-item--detail') if (!row) throw new Error('展开聚合行后没渲染出明细行') row.click() await flushPromises() expect(feedback.showAdminFeedback).not.toHaveBeenCalled() expect(panelRow('.bell-item--detail')?.className).not.toContain('bell-item--unread') expect(bell.find('.bell-badge').exists()).toBe(false) }) it('组内还有未读时红点不许掉,读完最后一条才掉', async () => { api.fetchNotificationGroups.mockResolvedValue( groupPage([group({ latestId: 32, rowCount: 2, unreadCount: 2 })], { unreadCount: 2, unreadGroupCount: 1 }), ) api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 32 }) api.fetchNotificationList.mockResolvedValue({ items: [notification({ id: 31 }), notification({ id: 32 })], total: 2, page: 1, pageSize: 50, unreadCount: 2, }) const bell = mountBell() await flushPromises() await bell.find('button.bell-trigger').trigger('click') await flushPromises() await expandFirstGroup() panelRow('.bell-item--detail.bell-item--unread')!.click() await flushPromises() expect(api.markNotificationRead).toHaveBeenCalledTimes(1) expect(bell.find('.bell-badge').exists()).toBe(true, '这一组还剩一条没读,红点不许先掉') panelRow('.bell-item--detail.bell-item--unread')!.click() await flushPromises() expect(api.markNotificationRead).toHaveBeenCalledTimes(2) expect(bell.find('.bell-badge').exists()).toBe(false) }) it('下钻带上主体用户:同场景同一天是好几组,少一维就把别的主体的行混进来', async () => { api.fetchNotificationGroups.mockResolvedValue( groupPage([group({ subjectUserId: 1196, latestId: 41 }), group({ subjectUserId: 1160, latestId: 42 })]), ) api.fetchNotificationList.mockResolvedValue({ items: [notification({ id: 41 })], total: 1, page: 1, pageSize: 50, unreadCount: 1, }) const bell = mountBell() await flushPromises() await bell.find('button.bell-trigger').trigger('click') await flushPromises() expect(document.body.querySelectorAll('.bell-group')).toHaveLength(2) await expandFirstGroup() expect(api.fetchNotificationList.mock.calls[0][0]).toMatchObject({ scene: 'service_down', day: '2026-09-13', subjectUserId: 1196, }) expect(api.fetchNotificationList.mock.calls[0][0].subjectUnlabelled).toBe(false) }) it('默认展示四级严重度并按严重度请求;切「时间」后带 sort=time 重查并恢复日期头', async () => { api.fetchNotificationGroups.mockResolvedValue( groupPage([ group({ latestId: 51, severity: 'urgent', level: 'error', day: '2026-09-13' }), group({ latestId: 50, subjectUserId: 1196, severity: 'low', level: 'info', day: '2026-09-12' }), ]), ) const bell = mountBell() await flushPromises() await bell.find('button.bell-trigger').trigger('click') await flushPromises() expect(Array.from(document.querySelectorAll('.bell-severity-tag')).map((el) => el.textContent?.trim())) .toEqual(['紧急', '低危']) expect(api.fetchNotificationGroups.mock.calls[0][0].sort).toBe('severity') // 严重度排序会跨天交错,不挂日期头 expect(document.querySelectorAll('.bell-day-head')).toHaveLength(0) // 展开明细也要带同一种排序,否则会出现「列表按严重度、明细又按时间」 api.fetchNotificationList.mockResolvedValue({ items: [notification({ id: 51, severity: 'urgent' })], total: 1, page: 1, pageSize: 50, unreadCount: 1, }) await expandFirstGroup() expect(api.fetchNotificationList.mock.calls.at(-1)?.[0].sort).toBe('severity') const timeButton = Array.from(document.querySelectorAll('.bell-sort-chips button')) .find((button) => button.textContent?.includes('时间')) expect(timeButton).toBeTruthy() timeButton!.click() await flushPromises() expect(api.fetchNotificationGroups.mock.calls.at(-1)?.[0].sort).toBe('time') expect(document.querySelectorAll('.bell-day-head')).toHaveLength(2) await expandFirstGroup() expect(api.fetchNotificationList.mock.calls.at(-1)?.[0].sort).toBe('time') }) })