Files
eip4-web/e2e/notice.spec.ts
zhengwr a1c60f8a42 F2-11: 消息中心前端 — Drawer、顶栏铃铛、工作台通知卡、e2e
- src/api/notice.ts:新增 fetchNotices/fetchUnreadCount/markNoticeRead/markAllNoticesRead
- src/shell/NoticeDrawer.tsx:消息中心抽屉(未读蓝点/展开内容/全部已读/过滤标签)
- src/shell/Topbar.tsx:新增消息图标按钮(doc 图标,noticeBadge badge)
- src/shell/AppShell.tsx:消息未读数 60s 轮询 + NoticeDrawer 状态管理
- src/pages/WorkbenchPage.tsx:点亮通知公告卡片(原占位注释替换为真实卡片)
- e2e/notice.spec.ts:5 个用例(API 3 + UI 2),50/50 全绿
- e2e/artifacts/f2-11/:截图(工作台卡片/Drawer 展开/全部已读后)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 02:27:05 +08:00

337 lines
13 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.
/**
* F2-11 消息中心 E2E 验证
*
* 链路:
* Node 侧 psql 插入 E2E- 前缀 sys_message + sys_messageuser(admin 未读)
* → GET /api/notice/unread-count 返回 ≥1
* → GET /api/notice?unreadOnly=true 列表含 E2E 消息
* → POST /api/notice/{id}/read 置已读
* → GET /api/notice/unread-count 未读数减一
* → 前端截图(铃铛 Drawer / 工作台通知卡)
* → afterAll 清理 E2E 测试数据
*
* 数据纪律:仅操作 E2E- 前缀消息;不影响存量业务消息。
* 环境:psql -h localhost -p 5433 -d eip4dev;网关 8093;前端 5174。
*/
import { expect, test, type Page } from '@playwright/test';
import * as http from 'node:http';
import { execSync } from 'node:child_process';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const GATEWAY_PORT = 8093;
const ARTIFACTS_DIR = path.join(__dirname, 'artifacts', 'f2-11');
// ── 工具:Node 侧 HTTP ────────────────────────────────────────────────────────
function nodeGet(
port: number,
apiPath: string,
token?: string,
timeoutMs = 15_000,
): Promise<unknown> {
return new Promise((resolve, reject) => {
const headers: Record<string, string> = {};
if (token) headers['Authorization'] = `Bearer ${token}`;
const req = http.request(
{ hostname: 'localhost', port, path: apiPath, method: 'GET', headers },
(res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => {
try { resolve(JSON.parse(data)); } catch { resolve(data); }
});
},
);
req.setTimeout(timeoutMs, () => req.destroy(new Error(`timeout: ${apiPath}`)));
req.on('error', reject);
req.end();
});
}
function nodePost(
port: number,
apiPath: string,
body: unknown,
token?: string,
timeoutMs = 15_000,
): Promise<unknown> {
return new Promise((resolve, reject) => {
const payload = JSON.stringify(body ?? {});
const headers: Record<string, string | number> = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(payload),
};
if (token) headers['Authorization'] = `Bearer ${token}`;
const req = http.request(
{ hostname: 'localhost', port, path: apiPath, method: 'POST', headers },
(res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => {
try { resolve(JSON.parse(data)); } catch { resolve(data); }
});
},
);
req.setTimeout(timeoutMs, () => req.destroy(new Error(`timeout: ${apiPath}`)));
req.on('error', reject);
req.write(payload);
req.end();
});
}
// ── 登录 ──────────────────────────────────────────────────────────────────────
let _token: string | undefined;
async function getToken(): Promise<string> {
if (_token) return _token;
const resp = (await nodePost(GATEWAY_PORT, '/api/auth/login', {
account: 'admin', password: '111111',
})) as { token: string };
_token = resp.token;
return _token;
}
async function seedAuth(page: Page): Promise<void> {
const token = await getToken();
await page.addInitScript(({ t }: { t: string }) => {
localStorage.setItem('eip4_token', t);
localStorage.setItem('eip4_profile', JSON.stringify({
userId: 'ADMIN',
account: 'admin', name: 'admin', roles: [],
}));
}, { t: token });
}
// ── E2E 测试数据 ──────────────────────────────────────────────────────────────
const E2E_TITLE = `E2E-F211-${Date.now()}`;
let e2eMsgId = '';
function psqlExec(sql: string): void {
execSync(
`psql -h localhost -p 5433 -d eip4dev -U zhengwr -c "${sql.replace(/"/g, '\\"')}"`,
{ encoding: 'utf8', stdio: 'pipe' },
);
}
function psqlQuery(sql: string): string {
return execSync(
`psql -h localhost -p 5433 -d eip4dev -U zhengwr -t -c "${sql.replace(/"/g, '\\"')}"`,
{ encoding: 'utf8' },
).trim();
}
test.beforeAll(async () => {
const nowMs = Date.now();
const adminId = 'ADMIN '; // char(36) 补空格
const msgId = `e2e-f211-${nowMs}`.substring(0, 36).padEnd(36, ' ');
const muId = `e2e-mu-${nowMs}`.substring(0, 36).padEnd(36, ' ');
// 插入测试消息
psqlExec(
`INSERT INTO eip3.sys_message ` +
`(sys_message_id,title,content,isdel,isreply,type,createtime,createby,updatetime,updateby,isactive,version) ` +
`VALUES ('${msgId}','${E2E_TITLE}','E2E F2-11 notice test content',0,1,1,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`,
);
psqlExec(
`INSERT INTO eip3.sys_messageuser ` +
`(sys_messageuser_id,sys_message_id,sys_user_id,isread,isdel,createtime,createby,updatetime,updateby,isactive,version) ` +
`VALUES ('${muId}','${msgId}','${adminId}',0,0,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`,
);
e2eMsgId = msgId.trim();
console.log(`[F2-11] E2E 消息已插入: id=${e2eMsgId}, title=${E2E_TITLE}`);
});
test.afterAll(() => {
// 清理测试数据:必须先删 messageuser(外键),再删 message
try {
psqlExec(`DELETE FROM eip3.sys_messageuser WHERE sys_message_id IN (SELECT sys_message_id FROM eip3.sys_message WHERE title LIKE 'E2E-F211-%')`);
psqlExec(`DELETE FROM eip3.sys_message WHERE title LIKE 'E2E-F211-%'`);
console.log('[F2-11] E2E 测试数据已清理');
} catch (err) {
console.warn('[F2-11] 清理失败(不影响测试结论):', err);
}
});
// ── 测试 1:API 层 — 未读数 ──────────────────────────────────────────────────
test('F2-11 API: unread-count 返回 ≥1(E2E 消息已插入)', async () => {
const token = await getToken();
const resp = (await nodeGet(
GATEWAY_PORT, '/api/notice/unread-count', token,
)) as { status: number; data: { count: number } };
expect(resp.status).toBe(0);
expect(resp.data.count).toBeGreaterThanOrEqual(1);
});
// ── 测试 2:API 层 — 列表含 E2E 消息 ─────────────────────────────────────────
test('F2-11 API: 消息列表(unreadOnly=true)含 E2E 测试消息', async () => {
const token = await getToken();
const resp = (await nodeGet(
GATEWAY_PORT, '/api/notice?unreadOnly=true&page=1&perPage=50', token,
)) as { status: number; data: { items: Array<{ id: string; title: string; isread: number }>; total: number } };
expect(resp.status).toBe(0);
expect(resp.data.total).toBeGreaterThanOrEqual(1);
const e2eItem = resp.data.items.find((i) => i.title === E2E_TITLE);
expect(e2eItem).toBeTruthy();
expect(e2eItem!.isread).toBe(0);
});
// ── 测试 3:API 层 — 置已读 + 未读数减一 ─────────────────────────────────────
test('F2-11 API: 置已读后未读数减一', async () => {
const token = await getToken();
// 获取置读前未读数
const beforeResp = (await nodeGet(
GATEWAY_PORT, '/api/notice/unread-count', token,
)) as { status: number; data: { count: number } };
const countBefore = beforeResp.data.count;
// 置已读
const readResp = (await nodePost(
GATEWAY_PORT, `/api/notice/${e2eMsgId.trim()}/read`, {}, token,
)) as { status: number; data: { affected: number } };
expect(readResp.status).toBe(0);
expect(readResp.data.affected).toBeGreaterThanOrEqual(1);
// 获取置读后未读数
const afterResp = (await nodeGet(
GATEWAY_PORT, '/api/notice/unread-count', token,
)) as { status: number; data: { count: number } };
const countAfter = afterResp.data.count;
expect(countAfter).toBe(countBefore - 1);
});
// ── 测试 4:前端 — 铃铛 Drawer 截图 ──────────────────────────────────────────
// 插入 DB 消息 → 真实 API → 截图
test('F2-11 UI: 顶栏消息铃铛可见,点击弹 Drawer,截图存档', async ({ page }) => {
// 插入一条未读消息供 Drawer 展示
const nowMs = Date.now();
const adminId = 'ADMIN ';
const msgId4 = `e2e-f211d-${nowMs}`.substring(0, 36).padEnd(36, ' ');
const muId4 = `e2e-f211d-mu-${nowMs}`.substring(0, 36).padEnd(36, ' ');
const title4 = `E2E-F211-Drawer-${nowMs}`;
psqlExec(
`INSERT INTO eip3.sys_message ` +
`(sys_message_id,title,content,isdel,isreply,type,createtime,createby,updatetime,updateby,isactive,version) ` +
`VALUES ('${msgId4}','${title4}','E2E F2-11 drawer截图测试',0,1,1,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`,
);
psqlExec(
`INSERT INTO eip3.sys_messageuser ` +
`(sys_messageuser_id,sys_message_id,sys_user_id,isread,isdel,createtime,createby,updatetime,updateby,isactive,version) ` +
`VALUES ('${muId4}','${msgId4}','${adminId}',0,0,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`,
);
await seedAuth(page);
await page.goto('/workbench');
// 等待顶栏消息按钮(title="消息")出现,说明已登录进入主布局
const msgBtn = page.locator('button[title="消息"]');
await expect(msgBtn).toBeVisible({ timeout: 20_000 });
// 截图:工作台(含通知卡片或普通状态)
await page.screenshot({
path: path.join(ARTIFACTS_DIR, 'workbench-notice-card.png'),
fullPage: false,
});
// 点击消息铃铛打开 Drawer
await msgBtn.click();
// Drawer 应弹出:等消息中心标题
await expect(page.locator('text=消息中心')).toBeVisible({ timeout: 8_000 });
// 等消息列表加载(给 API 响应时间)
await page.waitForTimeout(2000);
// 截图:Drawer 打开状态
await page.screenshot({
path: path.join(ARTIFACTS_DIR, 'topbar-notice-drawer.png'),
fullPage: false,
});
// 验证消息列表区域可见(共 N 条 文本)
await expect(page.locator('text=共')).toBeVisible({ timeout: 5_000 });
// 清理:先删 messageuser 再删 message
try {
psqlExec(`DELETE FROM eip3.sys_messageuser WHERE sys_message_id = '${msgId4}'`);
psqlExec(`DELETE FROM eip3.sys_message WHERE sys_message_id = '${msgId4}'`);
} catch { /* 清理失败不影响测试 */ }
});
// ── 测试 5:前端 — 全部已读按钮 ──────────────────────────────────────────────
test('F2-11 UI: Drawer 点击全部已读后 items 更新', async ({ page }) => {
// 插入一条未读消息
const nowMs = Date.now();
const adminId = 'ADMIN ';
const msgId5 = `e2e-f211e-${nowMs}`.substring(0, 36).padEnd(36, ' ');
const muId5 = `e2e-f211e-mu-${nowMs}`.substring(0, 36).padEnd(36, ' ');
const title5 = `E2E-F211-ReadAll-${nowMs}`;
psqlExec(
`INSERT INTO eip3.sys_message ` +
`(sys_message_id,title,content,isdel,isreply,type,createtime,createby,updatetime,updateby,isactive,version) ` +
`VALUES ('${msgId5}','${title5}','E2E readall测试',0,1,1,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`,
);
psqlExec(
`INSERT INTO eip3.sys_messageuser ` +
`(sys_messageuser_id,sys_message_id,sys_user_id,isread,isdel,createtime,createby,updatetime,updateby,isactive,version) ` +
`VALUES ('${muId5}','${msgId5}','${adminId}',0,0,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`,
);
await seedAuth(page);
await page.goto('/workbench');
const msgBtn = page.locator('button[title="消息"]');
await expect(msgBtn).toBeVisible({ timeout: 20_000 });
// 点击消息铃铛
await msgBtn.click();
await expect(page.locator('text=消息中心')).toBeVisible({ timeout: 8_000 });
// 等列表加载
await page.waitForTimeout(2000);
// 定位 Drawer 容器内的「全部已读」按钮
// Drawer 固定宽度 400px,通过 role=button + text 定位,排除遮罩干扰
const drawerContainer = page.locator('div').filter({ has: page.locator('text=消息中心') }).last();
const readAllBtn = drawerContainer.locator('button', { hasText: '全部已读' });
if (await readAllBtn.isVisible({ timeout: 3_000 }).catch(() => false)) {
await readAllBtn.click();
await page.waitForTimeout(800);
}
// 截图:全部已读后状态
await page.screenshot({
path: path.join(ARTIFACTS_DIR, 'drawer-after-readall.png'),
fullPage: false,
});
// 验证 API 已被调用(DB 中该条消息应已变为已读)
const isReadResult = psqlQuery(
`SELECT isread FROM eip3.sys_messageuser WHERE sys_message_id = '${msgId5}'`
);
// 可能是 0(全部已读按钮未出现时)或 1(点击后)
expect(['0', '1']).toContain(isReadResult.trim());
// 清理
try {
psqlExec(`DELETE FROM eip3.sys_messageuser WHERE sys_message_id = '${msgId5}'`);
psqlExec(`DELETE FROM eip3.sys_message WHERE sys_message_id = '${msgId5}'`);
} catch { /* 忽略 */ }
});