Files
persionalBrand/apps/taro/test/browser/template-management.spec.ts
que01 84522a8908
CI / Static checks (pull_request) Successful in 5m52s
CI / Production build (pull_request) Successful in 5m35s
CI / Browser smoke (pull_request) Successful in 3m0s
CI / API integration (pull_request) Successful in 3m41s
test: 修复浏览器回归 fixture 契约漂移
- 补齐 trust content 与模板版本 fixture 的必填字段\n- mock template-operations/failures 的完整响应结构\n- 补全完整浏览器回归的启动步骤与 CORS 要求\n\n完整回归 32 个用例全部通过。
2026-10-21 16:37:31 +08:00

175 lines
8.3 KiB
TypeScript

import assert from "node:assert/strict";
import fs from "node:fs";
import { mkdirSync } from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { test, expect } from "@playwright/test";
// 使用真实包和生产投影生成 UI fixture;HTTP 授权与持久化由 API 集成测试覆盖。
const manifest = JSON.parse(
fs.readFileSync("../../packages/template-atelier-solopreneur/template.json", "utf8"),
);
const version = {
id: "preview-browser-version",
templatePackageId: "preview-browser-package",
packageKey: manifest.packageKey,
version: manifest.version,
displayName: manifest.displayName,
status: "imported",
contentChecksum: "fixture-checksum",
archiveChecksum: "fixture-archive-checksum",
importedAt: "2026-10-21T00:00:00.000Z",
updatedAt: "2026-10-21T00:00:00.000Z",
manifestSnapshot: manifest,
importedBy: { id: "template-admin", username: "admin", displayName: "模板管理员" },
validationReport: {},
manifestSummary: { supportedIndustryTemplates: manifest.supportedIndustryTemplates },
};
test("模板管理可重试预览,并切换我的、详情和禁止提交的咨询内页", async ({ page }) => {
// 独立 Node ESM 进程避免 Playwright CJS transform 改写 API 的 import-only 依赖。
const fixture = JSON.parse(
execFileSync(
process.execPath,
[
"--input-type=module",
"-e",
`
import 'reflect-metadata';
import { AdminTemplatePreviewService } from './dist/modules/admin/admin-template-preview.service.js';
import { AdminTemplatePreviewAssetsService } from './dist/modules/admin/admin-template-preview-assets.service.js';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
let input = '';
for await (const chunk of process.stdin) input += chunk;
const version = JSON.parse(input);
const temporary = mkdtempSync(path.join(os.tmpdir(), 'template-preview-browser-'));
try {
execFileSync(process.execPath, ['../../scripts/template-pack.cjs', '--template', version.packageKey, '--out', temporary], { stdio: 'ignore' });
const archive = readdirSync(temporary).find((file) => file.endsWith('.tar.gz'));
version.artifactPath = path.join(temporary, archive);
version.archiveChecksum = createHash('sha256').update(readFileSync(version.artifactPath)).digest('hex');
version.contentChecksum = JSON.parse(readFileSync(path.join(temporary, archive.slice(0, -7), 'checksums.json'), 'utf8')).contentChecksum;
const service = new AdminTemplatePreviewService({ templatePackageVersion: { findUnique: async () => version }, templatePackageAuditLog: { create: async () => ({}) } }, new AdminTemplatePreviewAssetsService());
process.stdout.write(JSON.stringify(await service.preview(version.id, 'personal', 'browser-fixture-admin')));
} finally { rmSync(temporary, { recursive: true, force: true }); }
`,
],
{ cwd: path.resolve("../api"), input: JSON.stringify(version), encoding: "utf8" },
),
);
await page.setViewportSize({ width: 1440, height: 1000 });
await page.route("**/api/**", (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
return route.fulfill({ json: {} });
});
let attempts = 0;
const writes: string[] = [];
const evidenceDirectory = process.env.TEMPLATE_PREVIEW_VISUAL_EVIDENCE;
const captureVisualEvidence = async (name: string) => {
if (!evidenceDirectory) return;
mkdirSync(evidenceDirectory, { recursive: true });
await page.screenshot({ path: path.join(evidenceDirectory, `${name}.png`) });
};
await page.route("**/api/**", async (route) => {
const url = new URL(route.request().url());
if (url.pathname.endsWith("/admin/session/current"))
return route.fulfill({
json: {
authenticated: true,
displayName: "模板管理员",
role: "owner",
mustChangePassword: false,
platformTemplateRole: "template_admin",
},
});
if (route.request().method() !== "GET") writes.push(url.pathname);
if (url.pathname.endsWith("/preview")) {
attempts++;
if (attempts === 1)
return route.fulfill({
status: 400,
json: { error: { code: "HTTP_400", message: "预览测试失败,请重试" } },
});
return route.fulfill({ json: fixture });
}
if (url.pathname.endsWith("/admin/templates"))
return route.fulfill({ json: { items: [version], page: 1, pageSize: 20, total: 1 } });
if (url.pathname.endsWith("/admin/template-operations/failures"))
return route.fulfill({
json: {
since: "2026-09-21T00:00:00.000Z",
until: "2026-10-21T00:00:00.000Z",
days: 30,
backfilled: true,
failures: [],
},
});
if (url.pathname.endsWith("/admin/brands")) return route.fulfill({ json: [] });
return route.fulfill({ json: { name: "测试工作区" } });
});
const adminPage = await page.goto(
`${process.env.ADMIN_URL || "http://localhost:3016"}/admin/templates`,
);
const contentSecurityPolicy = adminPage?.headers()["content-security-policy"];
assert.match(contentSecurityPolicy ?? "", /default-src 'self'/);
assert.match(contentSecurityPolicy ?? "", /img-src [^;]*data:/);
assert.match(contentSecurityPolicy ?? "", /frame-ancestors 'self'/);
await page.getByRole("button", { name: /预览/ }).click();
const modal = page.getByRole("dialog");
await expect(modal.getByText("预览测试失败,请重试")).toBeVisible();
await modal.getByRole("button", { name: /重试/ }).click();
await expect(modal.locator(".atelier-founder-name")).toHaveText(
manifest.previewFixture.personal.content.brandConfig.founder,
);
await expect(modal.getByText("演示数据:独立预览内容")).toBeVisible();
await modal.getByText("资源诊断", { exact: true }).click();
await expect(modal.getByText("内容缺失", { exact: true })).toHaveCount(0);
await expect(modal.getByText("包内资源已验证", { exact: true }).first()).toBeVisible();
await captureVisualEvidence("home");
const choosePage = async (label: string) => {
await modal.getByLabel("预览页面").click();
await page.locator(".ant-select-item-option-content").getByText(label, { exact: true }).click();
};
// 画布内真实 CTA 导航:首页案例进入详情,详情咨询进入表单。
await modal.locator(".atelier-case").first().click();
await expect(modal.locator(".atelier-detail-action")).toBeVisible();
await captureVisualEvidence("detail");
await modal.locator(".atelier-detail-action button").first().click();
await expect(modal.locator(".inquiry-form")).toBeVisible();
await captureVisualEvidence("inquiry");
await modal.getByLabel("预览页面").click();
await page.locator(".ant-select-item-option-content").getByText("首页", { exact: true }).click();
await modal.getByText("资源诊断", { exact: true }).click();
await expect(modal.getByText("内容缺失", { exact: true })).toHaveCount(0);
await expect(modal.getByText("包内资源已验证", { exact: true }).first()).toBeVisible();
await choosePage("我的");
await expect(modal.locator(".component-template-preview")).toContainText("我的咨询记录");
await captureVisualEvidence("profile");
await choosePage("业务详情");
await expect(modal.locator(".component-template-preview")).toContainText(
manifest.previewFixture.personal.content.offerings[0].name,
);
const caseImage = modal.locator('.component-template-preview img[src^="data:image/"]').first();
await expect(caseImage).toBeVisible();
await expect
.poll(() => caseImage.evaluate((image: HTMLImageElement) => image.naturalWidth))
.toBeGreaterThan(0);
await choosePage("咨询表单");
await expect(modal.locator(".inquiry-form")).toBeVisible();
await expect(modal.locator(".inquiry-form button").last()).toBeDisabled();
expect(writes).toEqual([]);
});