Files
eip4-web/e2e/designer.spec.ts
zhengwr dc9e424d06 F4-L1: amis-editor 页面设计器(多页入口隔离)+overlay 编辑闭环
- editor.html 独立 vite 入口,amis-editor npm 依赖与主应用本地 SDK 隔离
- 设计器:画布编辑/保存→overlay/还原标准版/预览;页面 Tab 管理员「设计」入口
- designer.spec.ts 7 用例(编辑→保存→渲染 overlay→还原,X-Schema-Layer 断言);全套 e2e 68/68

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-12 04:23:43 +08:00

297 lines
12 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.
/**
* F4-L1 页面设计器 e2e
*
* 闭环流程:
* 1. 取标准层 schema(Node 侧 API,断言 X-Schema-Layer: standard)
* 2. 保存 overlay(Node 侧 PUT)
* 3. GET 断言 X-Schema-Layer: overlay,schema 内容已更新
* 4. 浏览器打开 /page/:templateId,断言 amis-host 渲染(overlay 版)
* 5. 浏览器打开设计器 /editor.html?templateId=xxx(admin 可见)
* 6. 设计器加载完成(designer-root 或 designer-loading→designer-root)
* 7. 点击「还原标准版」按钮
* 8. GET 断言 X-Schema-Layer: standard(overlay 已删除)
* 9. 测后保证清理(afterAll DELETE overlay 幂等)
*
* 测试用 00511ac1-ee64-4ecd-a550-22842ee5be72(会议纪要归档表单),不污染业务模板。
* 数据纪律:测后 DELETE overlay 还原;断言响应头变化。
*/
import { expect, test, type Page } from '@playwright/test';
import http from 'node:http';
// ── 常量 ──────────────────────────────────────────────────────────────────
const TEST_TEMPLATE_ID = '00511ac1-ee64-4ecd-a550-22842ee5be72';
// overlay 用于测试的轻量 schema(保留 type:page,改 title 以便断言)
const OVERLAY_TITLE = 'E2E-Overlay-F4L1-测试定制标题';
const OVERLAY_SCHEMA = JSON.stringify({
type: 'page',
title: OVERLAY_TITLE,
body: [{ type: 'tpl', tpl: 'F4-L1 overlay 测试内容' }],
});
// ── Node 侧 http 工具 ──────────────────────────────────────────────────────
let _adminToken: string | undefined;
async function adminToken(): Promise<string> {
if (_adminToken) return _adminToken;
return new Promise((resolve, reject) => {
const body = JSON.stringify({ account: 'admin', password: '111111' });
const req = http.request(
{
hostname: 'localhost', port: 8093,
path: '/api/auth/login', method: 'POST',
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
},
(res) => {
let d = '';
res.on('data', (c) => (d += c));
res.on('end', () => {
const p = JSON.parse(d) as { success: boolean; token: string };
if (!p.success) return reject(new Error('admin login failed'));
_adminToken = p.token;
resolve(p.token);
});
},
);
req.on('error', reject);
req.write(body);
req.end();
});
}
/** Node 侧 GET,返回 {body, headers, status} */
async function apiGet(path: string): Promise<{ body: string; headers: Record<string, string | string[] | undefined>; status: number }> {
const tok = await adminToken();
return new Promise((resolve, reject) => {
const req = http.request(
{
hostname: 'localhost', port: 8093,
path, method: 'GET',
headers: { Authorization: `Bearer ${tok}`, 'Cache-Control': 'no-cache' },
},
(res) => {
let d = '';
res.on('data', (c) => (d += c));
res.on('end', () =>
resolve({ body: d, headers: res.headers as Record<string, string | string[] | undefined>, status: res.statusCode ?? 0 }),
);
},
);
req.on('error', reject);
req.end();
});
}
/** Node 侧 PUT,返回解析后 JSON */
async function apiPut(path: string, body: string): Promise<Record<string, unknown>> {
const tok = await adminToken();
return new Promise((resolve, reject) => {
const req = http.request(
{
hostname: 'localhost', port: 8093,
path, method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
Authorization: `Bearer ${tok}`,
},
},
(res) => {
let d = '';
res.on('data', (c) => (d += c));
res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
},
);
req.on('error', reject);
req.write(body);
req.end();
});
}
/** Node 侧 DELETE,返回解析后 JSON */
async function apiDelete(path: string): Promise<Record<string, unknown>> {
const tok = await adminToken();
return new Promise((resolve, reject) => {
const req = http.request(
{
hostname: 'localhost', port: 8093,
path, method: 'DELETE',
headers: { Authorization: `Bearer ${tok}` },
},
(res) => {
let d = '';
res.on('data', (c) => (d += c));
res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
},
);
req.on('error', reject);
req.end();
});
}
// ── 种入 admin session(browser 侧) ────────────────────────────────────────
async function seedAdminAuth(page: Page) {
const tok = await adminToken();
await page.addInitScript(
({ t }: { t: string }) => {
localStorage.setItem('eip4_token', t);
localStorage.setItem(
'eip4_profile',
JSON.stringify({ userId: 'ADMIN', account: 'admin', name: '系统管理员', roles: [] }),
);
},
{ t: tok },
);
}
// ── 测后清理 ───────────────────────────────────────────────────────────────
test.afterAll(async () => {
// 幂等删除 overlay(保证还原标准版)
await apiDelete(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`).catch(() => {});
});
// ============================================================================
// 测试套件
// ============================================================================
test.describe('F4-L1 设计器 overlay 协议', () => {
test('1. 标准层 GET 返回 X-Schema-Layer: standard', async () => {
// 先确保无 overlay(幂等 DELETE)
await apiDelete(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`).catch(() => {});
const { headers, status } = await apiGet(`/api/page/schema/${TEST_TEMPLATE_ID}`);
expect(status).toBe(200);
expect(headers['x-schema-layer']).toBe('standard');
});
test('2. PUT overlay 保存成功,返回 status:0', async () => {
const result = await apiPut(
`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`,
OVERLAY_SCHEMA,
);
expect(result['status']).toBe(0);
const data = result['data'] as Record<string, unknown>;
expect(data['templateId']).toBe(TEST_TEMPLATE_ID);
expect(typeof data['etag']).toBe('string');
expect((data['etag'] as string).length).toBe(64); // sha256 hex
});
test('3. PUT overlay 后 GET 返回 X-Schema-Layer: overlay,title 已更新', async () => {
const { body, headers, status } = await apiGet(`/api/page/schema/${TEST_TEMPLATE_ID}`);
expect(status).toBe(200);
expect(headers['x-schema-layer']).toBe('overlay');
const schema = JSON.parse(body) as Record<string, unknown>;
expect(schema['title']).toBe(OVERLAY_TITLE);
});
test('4. ?layer=standard 强制取标准层,X-Schema-Layer: standard', async () => {
const { headers, status } = await apiGet(
`/api/page/schema/${TEST_TEMPLATE_ID}?layer=standard`,
);
expect(status).toBe(200);
expect(headers['x-schema-layer']).toBe('standard');
});
test('5. /page/:templateId 浏览器渲染 overlay 版(amis-host 可见)', async ({ page }) => {
await seedAdminAuth(page);
await page.goto(`/page/${TEST_TEMPLATE_ID}`);
// 等待 amis 渲染宿主出现(最多 30s)
await page.waitForSelector('[data-testid="amis-host"]', { timeout: 30000 });
// 无 schema 错误卡片
await expect(page.locator('[data-testid="schema-error-card"]')).toHaveCount(0);
// 管理员可见「设计」按钮
await expect(page.locator('[data-testid="designer-open-btn"]')).toBeVisible();
});
test('6. 设计器页面加载(editor.html)—— designer-root 出现', async ({ page }) => {
await seedAdminAuth(page);
await page.goto(`/editor.html?templateId=${TEST_TEMPLATE_ID}`);
// 等待设计器根节点(loading → root,最多 60s,amis-editor 首次加载较慢)
await page.waitForSelector('[data-testid="designer-root"]', { timeout: 60000 });
// 顶部工具条可见
await expect(page.locator('[data-testid="designer-topbar"]')).toBeVisible();
// 保存/还原/预览按钮可见
await expect(page.locator('[data-testid="designer-btn-save"]')).toBeVisible();
await expect(page.locator('[data-testid="designer-btn-restore"]')).toBeVisible();
await expect(page.locator('[data-testid="designer-btn-preview"]')).toBeVisible();
// overlay badge 可见(当前是 overlay 状态)
await expect(page.locator('[data-testid="designer-overlay-badge"]')).toBeVisible();
// 截图:设计器加载完成(画布编辑状态)
await page.screenshot({
path: 'e2e/artifacts/f4-l1/01-designer-canvas.png',
fullPage: false,
});
});
test('7. 设计器「还原标准版」→ GET 返回 X-Schema-Layer: standard', async ({ page }) => {
// 先确保 overlay 存在(前序 test 可能已删)
await apiPut(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`, OVERLAY_SCHEMA);
await seedAdminAuth(page);
await page.goto(`/editor.html?templateId=${TEST_TEMPLATE_ID}`);
await page.waitForSelector('[data-testid="designer-root"]', { timeout: 60000 });
// 等还原按钮可交互(amis-editor 完全初始化后才 enabled)
await page.waitForSelector('[data-testid="designer-btn-restore"]:not([disabled])', { timeout: 30000 });
// 点击还原标准版
await page.click('[data-testid="designer-btn-restore"]');
// 等待成功 Toast
await page.waitForSelector('[data-testid="designer-toast-success"]', { timeout: 30000 });
// 截图:还原成功提示
await page.screenshot({
path: 'e2e/artifacts/f4-l1/02-designer-restore-toast.png',
fullPage: false,
});
// Node 侧验证 X-Schema-Layer 回到 standard
const { headers } = await apiGet(`/api/page/schema/${TEST_TEMPLATE_ID}`);
expect(headers['x-schema-layer']).toBe('standard');
});
test('8. 还原后 /page/:templateId 渲染标准版(无 overlay)', async ({ page }) => {
await seedAdminAuth(page);
await page.goto(`/page/${TEST_TEMPLATE_ID}`);
await page.waitForSelector('[data-testid="amis-host"]', { timeout: 30000 });
await expect(page.locator('[data-testid="schema-error-card"]')).toHaveCount(0);
// 截图:渲染标准版效果
await page.screenshot({
path: 'e2e/artifacts/f4-l1/03-render-standard-after-restore.png',
fullPage: false,
});
});
});
test.describe('F4-L1 设计器「保存」按钮流程', () => {
test('9. 设计器点击「保存」→ overlay 更新 → Toast 成功', async ({ page }) => {
// 先确保有 overlay(PUT 一个初始版本)
await apiPut(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`, OVERLAY_SCHEMA);
await seedAdminAuth(page);
await page.goto(`/editor.html?templateId=${TEST_TEMPLATE_ID}`);
await page.waitForSelector('[data-testid="designer-root"]', { timeout: 60000 });
// 点击保存(当前 schema 即 currentSchemaRef 的值)
await page.click('[data-testid="designer-btn-save"]');
await page.waitForSelector('[data-testid="designer-toast-success"]', { timeout: 15000 });
// 截图:保存提示
await page.screenshot({
path: 'e2e/artifacts/f4-l1/04-designer-save-toast.png',
fullPage: false,
});
// 验证 overlay 仍然存在
const { headers } = await apiGet(`/api/page/schema/${TEST_TEMPLATE_ID}`);
expect(headers['x-schema-layer']).toBe('overlay');
// 清理
await apiDelete(`/api/page/schema/${TEST_TEMPLATE_ID}/overlay`).catch(() => {});
});
});