Files
novalon-website/e2e/website-acceptance.spec.ts
T
zhangxiang eba4e10442 test(e2e): 覆盖分母补齐 + GA 断言与 opt-in 实现对齐
三件事同批,共同点是「门禁/断言与实现脱钩,而脱钩处恰好没人跑」。

1. GA4 consent 断言(新发现,上一轮遗留)
   DEF-09 把 analytics_storage 默认从 granted 改成 denied(opt-in),
   实现与单测都改了,e2e/ga4-event-tracking.spec.ts:132 仍断言 granted。
   它能藏住是因为那 4 个 @critical 用例**只在 test:e2e:prod 下真正执行**
   (dev 下 NEXT_PUBLIC_GA_MEASUREMENT_ID 不存在 ⇒ test.skip)⇒ 本地全绿看不见。
   改为同时钉两件事:default 必须是 denied;已存偏好由内联片段在 config
   之前以 consent update 放行。只改前者会让「偏好回放坏了」变成新盲区。
   判据:E2E_TARGET=production 跑 ga4 spec ⇒ 4 passed。

2. UJ-10 假红(TA-11)
   原断言「分类后恰 1 篇 / 全部恰 2 篇」,并行写库用例插入的 E2E 新闻会让它假红。
   改为钉两篇种子 slug 的可见/缺席 —— 比数条数更具体:数条数只证明「有 1 条」,
   钉 slug 才证明「筛掉的是另一类」。桌面 + 移动两份同步改。

3. 覆盖分母 + 取样稳定性
   - headings PAGES 11 → 34 页(与 check:axe:routes 的 35 条对齐,去掉按 404
     契约的 /_not-found)。实测 34/34 通过、0 问题。此前只扫 11 页,
     新增路由失踪时门禁仍然绿 —— 「分母静默变小」的第三种形态。
   - axe settle() 改逐屏 max(400, 0.8×viewport) 步进 + 双 rAF,回顶后等
     main * 内 opacity:0 元素清零(8s 超时抛出,不吞)。原「一次跳到底」
     会跳过 IntersectionObserver 目标,半透明文字被读成低对比度,失败集合漂移。
   - website-acceptance 的 pollBoundingBox 由「非空即返回」改为连续 5 次取样
     一致再返回(TA-12):页面入场 transform 未落定时会抓到 29.936px 中途值。
     超时仍 throw,判据强度不降。

判据:type-check / type-check:e2e EXIT=0;test:e2e:prod 135 passed / 0 failed
/ 9 skipped / EXIT=0;check:axe 35 路由 × 4 组合 140 rows 全 0、规则级 105/105。
2026-11-26 20:03:20 +08:00

313 lines
15 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.
import { test, expect, type Locator } from './fixtures';
import { primaryNav } from './primary-nav';
import { expectHydrated } from './hydrated';
interface BoxLike {
x: number;
y: number;
width: number;
height: number;
}
/**
* N-27 修复辅助:轮询直到 boundingBox 非空并返回它。
* 旧写法 `const box = await expect.poll(() => el.boundingBox()).not.toBeNull()` 的
* await 结果是 undefined(断言不产数),随后的 `if (box)` 恒假 ⇒ 几何断言全部死代码。
* 本函数把「等到非空」与「拿到值」分开,且拿不到值直接 throw(元素消失 ⇒ 用例失败)。
*
* 2026-10-17(§14)再修一次自身的竞态:上一版先 `expect.poll` 等到非空,
* **再单独调一次** `boundingBox()` 取值 —— 两次读取之间若赶上 header hydration 重挂
* (实测探针:加载期无「双字标可见」窗口,只有 t≈43ms 时 header 尚未进 DOM 的一瞬,
* 采样步长 60ms 抓不到的亚 60ms 卸载也足以让第二次读取返回 null),
* 就会把「值拿到了但那一瞬间元素换了节点」误报成「元素在断言瞬间消失」。
* ⇒ 改成在**同一次读取**里既判非空又产出值:读到非空立即返回,超时才 throw。
* 判据强度不降:仍然要求最终拿到一个非空 box 并做几何断言,也没有 catch/静默通过。
*
* 2026-10-24(TA-12)第三次修:**非空 ≠ 已落定**。页面入场 transform 未结束时,
* fixed header 的 boundingBox 会短暂偏移——实测抓到 29.936px 的中途值,
* 断言把它当最终值判红/判绿都是错的读数。改为要求连续 5 次取样一致(`stable >= 4`)再返回。
* 注意这不是「放宽判据」:它把「读到任意一帧」收紧成「读到稳定帧」,
* 而超时仍然 throw(元素一直不存在 / 一直在动 ⇒ 用例失败)。
*/
async function pollBoundingBox(target: Locator, timeout = 5000): Promise<BoxLike> {
const deadline = Date.now() + timeout;
let lastMissing = 0;
let last: BoxLike | null = null;
let stable = 0;
const near = (a: BoxLike, b: BoxLike) =>
Math.abs(a.x - b.x) < 0.5 && Math.abs(a.y - b.y) < 0.5
&& Math.abs(a.width - b.width) < 0.5 && Math.abs(a.height - b.height) < 0.5;
for (;;) {
const box = await target.boundingBox().catch(() => null);
if (box) {
stable = last && near(last, box) ? stable + 1 : 0;
if (stable >= 4) return box;
last = box;
} else {
last = null;
stable = 0;
lastMissing += 1;
}
if (Date.now() > deadline) {
throw new Error(
`boundingBox 在 ${timeout}ms 内未稳定(轮询 ${lastMissing} 次未拿到几何 ⇒ 元素不存在或不可见)`,
);
}
await new Promise((r) => setTimeout(r, 50));
}
}
test.describe('网站全面测试验收', { tag: '@regression' }, () => {
test.beforeEach(async ({ page }) => {
await page.goto('/', { waitUntil: 'domcontentloaded', timeout: 30000 });
});
test('首页加载正常', async ({ page }) => {
await expect(page).toHaveTitle(/四川睿新致远科技有限公司/);
await expect(page.locator('header')).toBeVisible();
await expect(page.locator('[data-testid="footer"]')).toBeVisible();
});
test('公司Logo可见且不被覆盖', async ({ page }) => {
// N-27:去掉 `if (logoBox && headerBox)`(其值恒为 undefined,见 pollBoundingBox)
// 与 `if (logoCount === 0)` 双分支守卫。logo 锚定 header「返回首页」链接内
// 按当前主题可见的那张 img(src/components/layout/header.tsx:96-122 明暗双版,
// globals.css 按 html[data-theme] 显隐 ⇒ 恒有一张可见)。
const logo = page.locator('header a[aria-label="返回首页"] img:visible').first();
await expect(logo).toBeVisible({ timeout: 10000 });
const logoBox = await pollBoundingBox(logo);
const headerBox = await pollBoundingBox(page.locator('header'));
expect(logoBox.x).toBeGreaterThanOrEqual(headerBox.x);
expect(logoBox.y).toBeGreaterThanOrEqual(headerBox.y);
expect(logoBox.x + logoBox.width).toBeLessThanOrEqual(headerBox.x + headerBox.width);
expect(logoBox.y + logoBox.height).toBeLessThanOrEqual(headerBox.y + headerBox.height);
});
test('导航菜单功能正常', async ({ page }) => {
// 桌面走顶栏、移动走抽屉;原因见 primary-nav.ts。
// N-27:原实现零断言,仅靠 `waitForURL(/\/.+/)` 隐式放行(任何路径变化都算过)。
// 改为断言「点击的链接确实落到它自己声明的 href」(同 p2 已修用例的口径)。
//
// 2026-10-17(§14.4):firefox/webkit 上偶发 `waitForURL` 15s 超时,日志显示
// 「navigated to http://localhost:3000/」——即点击落在了 logo(href="/")而不是导航链接。
// 两个原因一起修,断言不减:
// ① 缺 `expectHydrated(nav)`:hydration 期间的布局位移会让点击命中错位目标
// (同文件相邻用例早就有这个前置,这条漏了);
// ② 选择器 `a[href^="/"]` 会把 logo 算进来 ⇒ 改为排除 `href="/"`,
// 让「导航菜单」测的真的是菜单项。
const nav = await primaryNav(page);
await expectHydrated(nav);
const link = nav.locator('a[href^="/"]:not([href="/"])').first();
await expect(link).toBeVisible();
const href = await link.getAttribute('href');
if (!href) {
throw new Error('首个导航链接缺少 href,无法判定跳转目标');
}
await Promise.all([
page.waitForURL((url) => url.pathname === href, {
waitUntil: 'commit',
timeout: 15000,
}),
link.click(),
]);
await expect(page).toHaveURL((url) => url.pathname === href);
});
test('联系我们页面没有显示公司电话', async ({ page }) => {
await page.goto('/contact', { waitUntil: 'load' });
await page.waitForTimeout(2000);
// N-27:去掉 `if (isVisible)` 守卫。联系信息区块由 contact-content-v3.tsx:316 的
// data-testid="contact-info" 无条件渲染(N-27 复核已确认存在);区块消失 ⇒ 本例失败。
const contactInfoSection = page.locator('[data-testid="contact-info"]');
await expect(contactInfoSection).toBeVisible();
const phoneInContactInfo = contactInfoSection.locator(
'text=/电话|028-88888888|联系电话/',
);
expect(await phoneInContactInfo.count()).toBe(0);
});
test('联系我们页面表单正常显示', async ({ page }) => {
await page.goto('/contact', { waitUntil: 'load' });
// 等待 React 客户端渲染完成
await page.waitForTimeout(2000);
await expect(page.locator('[data-testid="name-input"]')).toBeVisible();
await expect(page.locator('[data-testid="phone-input"]')).toBeVisible();
await expect(page.locator('[data-testid="email-input"]')).toBeVisible();
await expect(page.locator('[data-testid="subject-input"]')).toBeVisible();
await expect(page.locator('[data-testid="message-input"]')).toBeVisible();
await expect(page.locator('[data-testid="submit-button"]')).toBeVisible();
});
test('ICP备案号正确显示', async ({ page }) => {
const footer = page.locator('[data-testid="footer"], footer');
await expect(footer).toBeVisible();
const icpText = await footer.textContent();
expect(icpText).toContain('蜀ICP备2026013658号');
});
test('关于我们页面没有显示公司电话', async ({ page }) => {
await page.goto('/about', { waitUntil: 'load' });
await page.waitForTimeout(2000);
// N-27:原实现是「contactTexts 存在 → 遍历 → 第一个 visible 父级断言无电话 → break」,
// 三重守卫下 /about 没有「联系我们」文案时整例静默通过。改为对正文整体做无条件负断言:
// 页面上任何位置出现电话样式 ⇒ 失败;正文本身消失同样失败。
const mainContent = page.locator('main').first();
await expect(mainContent).toBeVisible();
const mainText = (await mainContent.textContent()) ?? '';
expect(mainText.length).toBeGreaterThan(100);
expect(mainText).not.toMatch(/028-\d{8}|1[3-9]\d{9}|联系电话|电话:/);
});
test('响应式设计正常工作', async ({ page }) => {
await page.setViewportSize({ width: 375, height: 667 });
await expect(page.locator('header')).toBeVisible();
await expect(page.locator('[data-testid="footer"], footer')).toBeVisible();
const mobileMenuButton = page.locator('[data-testid="mobile-menu-button"]');
await expect(mobileMenuButton).toBeVisible({ timeout: 5000 });
await expectHydrated(mobileMenuButton);
await mobileMenuButton.click();
await expect(page.locator('[data-testid="mobile-navigation"]')).toBeVisible({ timeout: 5000 });
});
test('页面跳转功能正常', async ({ page }) => {
// N-27:原实现两条点击都包在 `if (isVisible)` 里——移动 project 顶栏(hidden md:flex)
// 不存在 ⇒ 两个守卫恒假,整例静默通过;且 `waitForURL(/\//)` 恒真。
// 固定桌面视口后本例验证的就是桌面顶栏的两段跳转,守卫改为硬断言。
// 顶栏没有 a[href="/"](NAVIGATION_V2 无首页项,src/lib/constants/navigation.ts:45-53),
// 回首页的真实入口是 logo 链接(header.tsx:96 的 aria-label="返回首页")。
await page.setViewportSize({ width: 1280, height: 800 });
await page.goto('/', { waitUntil: 'domcontentloaded', timeout: 30000 });
const nav = page.getByTestId('desktop-navigation');
await expect(nav).toBeVisible();
await expectHydrated(nav);
// 桌面顶栏里没有 `a[href="/contact"]`:NAVIGATION_V2 只有 行业/能力/洞察/关于我们 四项,
// 联系入口是 header.tsx:165 的常驻 CTA(data-testid="consult-button",aria-label「预约咨询」),
// 位于 desktop-navigation 之外。注释里那句「联系我们不在列表里」就是这条设计决定。
const contactLink = page.getByTestId('consult-button').first();
await expect(contactLink).toBeVisible();
await Promise.all([
page.waitForURL((url) => url.pathname === '/contact', {
waitUntil: 'commit',
timeout: 15000,
}),
contactLink.click(),
]);
await expect(page).toHaveURL((url) => url.pathname === '/contact');
const homeLink = page.locator('header a[aria-label="返回首页"]');
await expect(homeLink).toBeVisible();
await Promise.all([
page.waitForURL((url) => url.pathname === '/', {
waitUntil: 'commit',
timeout: 15000,
}),
homeLink.click(),
]);
await expect(page).toHaveURL((url) => url.pathname === '/');
});
test('Footer链接正常工作', async ({ page }) => {
const footer = page.locator('footer').first();
await expect(footer).toBeVisible({ timeout: 10000 });
// Check footer contains expected links and legal info
const footerText = await footer.textContent();
expect(footerText).toContain('ICP');
expect(footerText).toContain('隐私');
});
test('表单验证功能正常', async ({ page }) => {
await page.goto('/contact', { waitUntil: 'domcontentloaded' });
// 联系表单是 'use client' 组件,需等待 hydration 完成后再交互
const submitButton = page.locator('[data-testid="submit-button"]');
await expect(submitButton).toBeVisible({ timeout: 15000 });
await expectHydrated(submitButton);
await submitButton.click();
// 等待 Zod 验证错误渲染(客户端校验触发后 DOM 更新)
const errorMessages = page.locator('[data-testid="error-message"]');
await expect(errorMessages.first()).toBeVisible({ timeout: 10000 });
const errorCount = await errorMessages.count();
expect(errorCount).toBeGreaterThan(0);
});
test('页面加载性能良好', async ({ page }) => {
// 确保访问本地服务器而非外部域名
await page.goto('/', { waitUntil: 'load', timeout: 30000 });
const performanceMetrics = await page.evaluate(() => {
const navigation = performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming;
return {
domContentLoaded: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart,
loadComplete: navigation.loadEventEnd - navigation.loadEventStart,
};
});
expect(performanceMetrics.domContentLoaded).toBeLessThan(5000);
expect(performanceMetrics.loadComplete).toBeLessThan(15000);
});
test('无障碍访问正常', async ({ page }) => {
const htmlLang = await page.locator('html').getAttribute('lang');
expect(htmlLang).toBeTruthy();
// Skip link 通过 CSS left-[-9999px] 视觉隐藏,仅在 focus 时显示(标准无障碍模式)
// 使用 toBeAttached 验证 DOM 存在性而非视觉可见性
const skipLink = page.locator('[data-skip-to-content]');
await expect(skipLink).toBeAttached();
expect(await skipLink.textContent()).toContain('跳转到主要内容');
const main = page.locator('main').first();
await expect(main).toBeVisible({ timeout: 10000 });
// Check for navigation and footer existence (structure may vary)
const footer = page.locator('footer').first();
await expect(footer).toBeVisible({ timeout: 5000 });
const focusableElements = page.locator('a, button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
const focusCount = await focusableElements.count();
expect(focusCount).toBeGreaterThan(0);
});
test('联系我们页面没有返回按钮覆盖logo', async ({ page }) => {
await page.goto('/contact', { waitUntil: 'load' });
await page.waitForTimeout(2000);
// N-27:去掉四元 selector 探测 + `.catch(() => false)` 吞异常 + `if (logoBox && headerBox)`
// 死守卫。logo 恒为「返回首页」链接内按主题可见的那张 img(header.tsx:96-122)。
const logo = page.locator('header a[aria-label="返回首页"] img:visible').first();
await expect(logo).toBeVisible({ timeout: 10000 });
const logoBox = await pollBoundingBox(logo);
const headerBox = await pollBoundingBox(page.locator('header'));
const logoCenterX = logoBox.x + logoBox.width / 2;
const logoCenterY = logoBox.y + logoBox.height / 2;
expect(logoCenterX).toBeGreaterThan(headerBox.x);
expect(logoCenterX).toBeLessThan(headerBox.x + headerBox.width);
expect(logoCenterY).toBeGreaterThan(headerBox.y);
expect(logoCenterY).toBeLessThan(headerBox.y + headerBox.height);
// 意图的正面表达:logo 中心点上最顶端的元素必须仍属于 logo 链接本身,
// 若「返回按钮」等浮层再次盖住 logo,elementFromPoint 会返回浮层 ⇒ 用例失败。
const topElementClass = await page.evaluate(({ x, y }) => {
const el = document.elementFromPoint(x, y);
if (!el) return 'none';
const host = el.closest('a[aria-label="返回首页"]');
return host ? 'logo-link' : el.tagName.toLowerCase();
}, { x: logoCenterX, y: logoCenterY });
expect(topElementClass).toBe('logo-link');
});
});