/** * 首批组件挂载用例之二(四面9分口径 §2 后管「0 组件挂载测试」)。 * * 靶子是 NotificationBell.vue 的两处静默 catch(未读数轮询、点通知标已读)。 * 这里跑真组件:真 pinia 会话、真 `notification-bell-model` 里的提示闸门、真定时器 * (用 vi 的假时钟推进 60s 轮询),只把两个出口(api 与 admin-feedback-ui)换成可断言的假件 * ⇒ 判的是运行时行为,不是读源码的形状钉子。 * * ⚠ 面板是 ``:每支用例都必须 unmount 并清空 body, * 否则上一支留下的那一行 `.bell-item--unread` 会被这一支的 document 查询捡到(实测会串味)。 * * 跑法:`npm run test:mount`。 */ 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(() => ({ fetchNotificationSummary: 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, }) 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(): HTMLElement | null { return document.body.querySelector('.bell-item') as HTMLElement | null } beforeEach(() => { vi.clearAllMocks() pinia = createPinia() setActivePinia(pinia) useAdminSessionStore().user = { id: 9, username: 'root', role: 'super_admin' } api.fetchNotificationList.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 10, unreadCount: 0 }) api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 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, 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.fetchNotificationList.mockResolvedValue({ items: [notification({ id: 21 })], total: 1, page: 1, pageSize: 10, unreadCount: 1, }) api.markNotificationRead.mockRejectedValue(new Error('403 Forbidden')) const bell = mountBell() await flushPromises() await bell.find('button.bell-trigger').trigger('click') await flushPromises() const row = panelRow() if (!row) throw new Error('面板 Teleport 到 body 后没渲染出那一行通知') row.click() await flushPromises() expect(feedback.showAdminFeedback).toHaveBeenCalledWith('这条通知没能标记为已读:403 Forbidden', 'error') // 前端不许替后端宣布已读:行仍是未读态、徽标还在 expect(panelRow()?.className).toContain('bell-item--unread') expect(bell.find('.bell-badge').exists()).toBe(true) }) it('反向钉:标已读成功时一句提示都不许有,行也要真的转为已读', async () => { api.fetchNotificationList.mockResolvedValue({ items: [notification({ id: 22 })], total: 1, page: 1, pageSize: 10, unreadCount: 1, }) api.markNotificationRead.mockResolvedValue(true) const bell = mountBell() await flushPromises() await bell.find('button.bell-trigger').trigger('click') await flushPromises() const row = panelRow() if (!row) throw new Error('面板 Teleport 到 body 后没渲染出那一行通知') row.click() await flushPromises() expect(feedback.showAdminFeedback).not.toHaveBeenCalled() expect(panelRow()?.className).not.toContain('bell-item--unread') expect(bell.find('.bell-badge').exists()).toBe(false) }) })