Files
crawler-plugin/frontend-vue/tests/mount/notification-bell-failure.mount.test.ts
T
huangzd1997 86d78160fd feat(通知): 四级严重度与严重度/时间双排序,客户端与后台管理同步
通知表新增 severity(紧急/高危/中危/低危,V161),由 scene + level 推导且
不回改 level:老客户端配色不受影响,secret_balance 的余量偏低与欠费也能分档。
列表与聚合接口默认按严重度倒序(同档按时间倒序),sort=time 切纯时间排序;
聚合组取组内最高严重度。两端铃铛加彩色等级标签与排序切换,展开明细沿用
同一排序,严重度排序下隐藏会跨天误导的日期头。
2026-10-21 13:33:07 +08:00

332 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 用户端铃铛的组件挂载用例(四面9分口径 §2「错误静默 …;0 挂载测试」那一半句的执行证据)。
*
* 两组靶子:
* ① 三处失败的用户可见性——本面 src 下的 vue 组件里"只 console 不给用户看"的 catch 实测 5 处,
* 铃铛占 3 处(未读数轮询、组加载、点明细标已读)。轮询与组加载那两处是**有意**静默
* (源码注释声明"不打扰用户",组加载失败改在面板内给文案),这里钉的是"声明的意图真兑现";
* 标已读那一处改前是真静默——点了通知没反应、行也没转已读,用户只能反复点,本轮改成可见。
* ② 10-13 聚合改造(场景 × 自然日 × 用户)带出来的三条口径:点聚合行只展开不标已读、
* 红点按组数亮、组内没读完红点不许掉。这三条都只能在真组件上验,纯函数用例判不到 DOM 与状态联动。
*
* 跑真组件:真 api 桩、真 ElMessage 出口、真 DOM,判的是运行时行为,
* 不是读源码的形状钉子(那类钉子在本仓已占 25% 用例,见 §2 后管同源问题)。
*
* ⚠ 面板是 `<Teleport to="body">`:每支用例都必须 unmount 并清 body,
* 否则上一支留下的 `.bell-item--unread` 会被这一支的 document 查询捡到。
*
* 跑法:`npx vitest run --config vitest.config.ts`(在 frontend-vue 目录下)
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import NotificationBell from '@/shared/components/NotificationBell.vue'
const message = vi.hoisted(() => ({
error: vi.fn(),
warning: vi.fn(),
success: vi.fn(),
info: vi.fn(),
closeAll: vi.fn(),
}))
const api = vi.hoisted(() => ({
fetchNotificationSummary: vi.fn(),
fetchNotificationGroups: vi.fn(),
fetchNotificationList: vi.fn(),
markNotificationRead: vi.fn(),
markAllNotificationsRead: vi.fn(),
}))
vi.mock('element-plus', () => ({ ElMessage: message }))
vi.mock('@/shared/api/types/modules/notification.ts', () => ({
NOTIFICATION_CATEGORY_OPTIONS: [],
NOTIFICATION_SEVERITY_LABELS: { urgent: '紧急', high: '高危', medium: '中危', low: '低危' },
fetchNotificationSummary: api.fetchNotificationSummary,
fetchNotificationGroups: api.fetchNotificationGroups,
fetchNotificationList: api.fetchNotificationList,
markAllNotificationsRead: api.markAllNotificationsRead,
markNotificationRead: api.markNotificationRead,
}))
const notification = (over: Record<string, unknown> = {}) => ({
id: 7,
title: '品牌检测服务挂了',
content: '上游 503',
level: 'error',
read: false,
createdAt: new Date().toISOString(),
...over,
})
/** 聚合行:一条组 = 场景 × 自然日 × 主体用户,rowCount 是折叠前的明细条数。 */
const group = (over: Record<string, unknown> = {}) => ({
latestId: 7,
scene: 'brand_check_failed',
category: 'task_error',
day: '2026-09-13',
subjectUserId: 1160,
rowCount: 1,
unreadCount: 1,
level: 'error',
title: '品牌检测服务挂了',
content: '上游 503',
createdAt: new Date().toISOString(),
...over,
})
let wrapper: VueWrapper | null = null
/** 打开面板:触发 togglePanel ⇒ 内部 void loadPage(1),靠 flushPromises 等它落地。 */
async function openPanel() {
wrapper = mount(NotificationBell)
await flushPromises()
await wrapper.find('.bell-trigger').trigger('click')
await flushPromises()
}
/**
* 从 document 取节点、用原生 click 触发:面板是 Teleport 到 body 的,
* `wrapper.find()` 看不见里面的节点(实测 wrapper 查 `.bell-item` 得到空 wrapper
* 而 document 里那一行确实在),而 Vue 的 @click 监听挂在元素上,原生 click 照样生效。
*/
function clickElement(selector: string) {
const row = document.querySelector<HTMLElement>(selector)
expect(row, `面板里没有可点的 ${selector}`).not.toBeNull()
row!.click()
}
/** 展开第一个聚合行:聚合行上的点击只做展开,明细行才是要点的那些。 */
async function expandFirstGroup() {
clickElement('.bell-group')
await flushPromises()
}
/**
* 红点取自 wrapper 而不是 document:`mount()` 不挂 attachTo,组件自身(含 .bell-trigger 与
* 它里面的 .bell-badge)渲染在游离节点上,只有 Teleport 到 body 的面板才能在 document 里查到。
*/
function badgeText(): string | null {
const badge = wrapper?.find('.bell-badge')
return badge && badge.exists() ? badge.text() : null
}
describe('NotificationBell:三处失败的用户可见性', () => {
beforeEach(() => {
document.body.innerHTML = ''
localStorage.clear()
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 1, unreadGroupCount: 1, latestId: 7 })
api.fetchNotificationGroups.mockResolvedValue({
groups: [group()],
total: 1,
rowCount: 1,
unreadGroupCount: 1,
unreadCount: 1,
})
api.fetchNotificationList.mockResolvedValue({ items: [notification()], total: 1 })
api.markNotificationRead.mockResolvedValue(undefined)
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(console, 'log').mockImplementation(() => {})
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
document.body.innerHTML = ''
vi.restoreAllMocks()
vi.clearAllMocks()
})
it('点明细标已读失败:必须给一条带原因的错误提示,且不许把这一行冒充成已读', async () => {
api.markNotificationRead.mockRejectedValue(new Error('403 Forbidden'))
await openPanel()
await expandFirstGroup()
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(1)
clickElement('.bell-item--detail')
await flushPromises()
expect(message.error).toHaveBeenCalledTimes(1)
expect(String(message.error.mock.calls[0][0])).toContain('403 Forbidden')
// 失败就是失败:这一行还得看着是未读(否则用户以为点到了,实际服务端没落)
expect(document.querySelector('.bell-item--unread')).not.toBeNull()
})
it('反向钉:标已读成功时不产生任何提示,而这一行要真的转为已读', async () => {
await openPanel()
await expandFirstGroup()
// 挂载那一轮 refreshSummary 发现"有新通知"本来就会弹一条 warning(既有设计,不是缺陷),
// 所以先把账清掉——本用例判的是"点成功这个动作"不许再产生提示。
message.error.mockClear()
message.warning.mockClear()
clickElement('.bell-item--detail')
await flushPromises()
expect(message.error).not.toHaveBeenCalled()
expect(message.warning).not.toHaveBeenCalled()
expect(document.querySelector('.bell-item--unread')).toBeNull()
})
it('组加载失败:文案进面板本身,而不是弹一条全局消息打扰用户', async () => {
api.fetchNotificationGroups.mockRejectedValue(new Error('502 Bad Gateway'))
await openPanel()
expect(document.body.textContent).toContain('502 Bad Gateway')
expect(message.error).not.toHaveBeenCalled()
expect(document.querySelectorAll('.bell-item')).toHaveLength(0)
})
it('默认展示四级严重度并按严重度请求;切「时间」后带 sort=time 重查并恢复日期头', async () => {
api.fetchNotificationGroups.mockResolvedValue({
groups: [
group({ latestId: 9, severity: 'urgent', level: 'error', day: '2026-09-13' }),
group({ latestId: 8, subjectUserId: 1160, severity: 'low', level: 'info', day: '2026-09-12' }),
],
total: 2,
rowCount: 2,
unreadGroupCount: 2,
unreadCount: 2,
})
await openPanel()
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: 9, 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<HTMLElement>('.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')
})
})
describe('NotificationBell:聚合两级与红点口径', () => {
beforeEach(() => {
document.body.innerHTML = ''
localStorage.clear()
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 7 })
api.fetchNotificationGroups.mockResolvedValue({
groups: [group({ latestId: 13, rowCount: 3, unreadCount: 2 })],
total: 1,
rowCount: 3,
unreadGroupCount: 1,
unreadCount: 2,
})
api.fetchNotificationList.mockResolvedValue({
items: [notification({ id: 11 }), notification({ id: 12 }), notification({ id: 13, read: true })],
total: 3,
})
api.markNotificationRead.mockResolvedValue(undefined)
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(console, 'log').mockImplementation(() => {})
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
document.body.innerHTML = ''
vi.restoreAllMocks()
vi.clearAllMocks()
})
it('点聚合行只展开:一次都不许替用户把通知标成已读', async () => {
await openPanel()
// 折叠态:面板里只有组行,一条明细都不该出现(明细要用户主动展开才拉)
expect(document.querySelectorAll('.bell-group')).toHaveLength(1)
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(0)
await expandFirstGroup()
expect(api.markNotificationRead).not.toHaveBeenCalled()
expect(api.fetchNotificationList).toHaveBeenCalledTimes(1)
// 下钻必须带上第三维(主体用户):同场景同一天里小魏11 与小魏17 是两组,
// 只按 scene+day 查会把两家的行都捞进同一份明细。
expect(api.fetchNotificationList.mock.calls[0][0]).toMatchObject({
scene: 'brand_check_failed',
day: '2026-09-13',
subjectUserId: 1160,
})
expect(api.fetchNotificationList.mock.calls[0][0].subjectUnlabelled).toBe(false)
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(3)
})
it('展开「未标注主体」那一组:按 IS NULL 查,不许把有主体的行混进来', async () => {
api.fetchNotificationGroups.mockResolvedValue({
groups: [group({ subjectUserId: null, rowCount: 2, unreadCount: 2 })],
total: 1,
rowCount: 2,
unreadGroupCount: 1,
unreadCount: 2,
})
await openPanel()
await expandFirstGroup()
const sent = api.fetchNotificationList.mock.calls[0][0]
expect(sent.subjectUnlabelled).toBe(true)
expect(sent.subjectUserId).toBeNull()
})
it('红点按组数亮、明细条数同屏:一组两条未读也不会亮成"2"', async () => {
await openPanel()
expect(badgeText()).toBe('1')
expect(document.querySelector('.bell-unread-chip')?.textContent).toContain('1 组未读')
// 组数与条数必须同时在屏上,只给一个数就会被读成"一共就这些通知"
expect(document.querySelector('.bell-foot-total')?.textContent).toContain('共 1 组')
expect(document.querySelector('.bell-foot-total')?.textContent).toContain('明细 3 条')
expect(document.querySelector('.bell-group-count')?.textContent).toBe('3 条 · 2 未读')
})
it('组内还有未读时红点不许掉,读完最后一条才掉', async () => {
await openPanel()
await expandFirstGroup()
clickElement('.bell-item--detail.bell-item--unread')
await flushPromises()
expect(api.markNotificationRead).toHaveBeenCalledTimes(1)
expect(badgeText()).toBe('1')
// 判组数必须看 chip:徽标在 unreadGroupCount 为 0 时会退回条数(兼容没给新字段的旧后端),
// 只钉徽标的话"组内没读完就把组数减掉"这条回归会被那层兜底盖住(变异自证 M2 实测存活过一次)。
expect(document.querySelector('.bell-unread-chip')?.textContent).toContain('1 组未读')
clickElement('.bell-item--detail.bell-item--unread')
await flushPromises()
expect(api.markNotificationRead).toHaveBeenCalledTimes(2)
// 这一组的两条未读都读完了:组数从 1 掉到 0,红点与"组未读"字样一起消失
expect(document.querySelector('.bell-badge')).toBeNull()
expect(document.querySelector('.bell-unread-chip')).toBeNull()
})
it('明细超出上限时说明还剩多少,不许让用户以为这就是全部', async () => {
api.fetchNotificationList.mockResolvedValue({
items: Array.from({ length: 50 }, (_, i) => notification({ id: 100 + i })),
total: 60,
})
await openPanel()
await expandFirstGroup()
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(50)
expect(document.querySelector('.bell-detail-state')?.textContent).toContain('另有 10 条未列出')
})
})