安全/鉴权:登出清服务端 httpOnly 令牌、登录 IP 限流前置 bcrypt、停用账号 令牌在 6 个内联 role handler 失效、admin/items 存在性 oracle 认证前置、 同意偏好 sanitize fail-closed、api-crypto 按 HTTP 方法判体。 CMS:workflow 状态更新+审计收进交互式 $transaction(失败即回滚)、编辑器 richtext 走 textarea 防换行损毁、array/object 子字段按作用域读写防污染、 about/contact/erp-upgrade 补 ISR revalidate 与路由映射。 UI/a11y:AnimatedCounter 入视口前显起点、CLS 累计上报、MetricCard 动画入 effect 并卸载取消 rAF、后台状态四态映射/搜索防抖+序号守卫/媒体单 input/ 吞错改横幅/表单 label-aria 关联。 新增对应判别性单测与 pagination/rate-limit/client-ip/sanitize/validate-content-data 等模块及 tests-integration 真库集成层。
508 lines
20 KiB
TypeScript
508 lines
20 KiB
TypeScript
import { describe, it, expect, jest, beforeEach, afterEach } from '@jest/globals';
|
||
import { render, screen } from '@testing-library/react';
|
||
import '@testing-library/jest-dom';
|
||
import HeroParticleField, { type HeroVariant } from './hero-particle-field';
|
||
|
||
// ─── Mocks ───────────────────────────────────────────────────────────────
|
||
// 本文件负责粒子引擎(绘制分支 / 出界回绕 / 启停),不做快照比对,
|
||
// 因此把 canvas 2d 上下文换成可回放的记录器:jsdom 无 canvas 实现,
|
||
// 不打桩的话 useEffect 会在 getContext('2d') 处提前 return(见 hero-particle-field.tsx:107)。
|
||
jest.mock('@/hooks/use-reduced-motion', () => ({
|
||
useReducedMotion: jest.fn(() => false),
|
||
}));
|
||
|
||
type Call = { op: string; args: unknown[] };
|
||
type StyleWrite = { prop: string; value: string };
|
||
interface CtxStub {
|
||
calls: Call[];
|
||
styles: StyleWrite[];
|
||
gradients: { addColorStop: jest.Mock }[];
|
||
}
|
||
|
||
function createCtxStub() {
|
||
const calls: Call[] = [];
|
||
const styles: StyleWrite[] = [];
|
||
const gradients: { addColorStop: jest.Mock }[] = [];
|
||
const record = (op: string) =>
|
||
jest.fn((...args: unknown[]) => {
|
||
calls.push({ op, args });
|
||
});
|
||
const stub: Record<string, unknown> = {
|
||
calls,
|
||
styles,
|
||
gradients,
|
||
setTransform: record('setTransform'),
|
||
clearRect: record('clearRect'),
|
||
beginPath: record('beginPath'),
|
||
moveTo: record('moveTo'),
|
||
lineTo: record('lineTo'),
|
||
stroke: record('stroke'),
|
||
arc: record('arc'),
|
||
fill: record('fill'),
|
||
createLinearGradient: jest.fn(() => {
|
||
const g = { addColorStop: jest.fn() };
|
||
gradients.push(g);
|
||
return g;
|
||
}),
|
||
};
|
||
for (const prop of ['lineWidth', 'globalAlpha', 'shadowColor', 'shadowBlur', 'strokeStyle', 'fillStyle']) {
|
||
let value: unknown = '';
|
||
Object.defineProperty(stub, prop, {
|
||
configurable: true,
|
||
get: () => value,
|
||
set: (next: unknown) => {
|
||
value = next;
|
||
styles.push({ prop, value: String(next) });
|
||
},
|
||
});
|
||
}
|
||
return stub as unknown as CanvasRenderingContext2D & CtxStub;
|
||
}
|
||
|
||
// ─── 环境夹具 ────────────────────────────────────────────────────────────
|
||
|
||
const VIEWPORT = { width: 1200, height: 700 };
|
||
const originalWebdriver = navigator.webdriver;
|
||
let ctxStub: CanvasRenderingContext2D & CtxStub;
|
||
let getCtxSpy: jest.SpiedFunction<typeof HTMLCanvasElement.prototype.getContext>;
|
||
let rectSpy: jest.SpiedFunction<typeof Element.prototype.getBoundingClientRect>;
|
||
let frameQueue: Array<(t: number) => void>;
|
||
let rafSpy: jest.SpiedFunction<typeof window.requestAnimationFrame>;
|
||
let cafSpy: jest.SpiedFunction<typeof window.cancelAnimationFrame>;
|
||
|
||
/** jsdom 里 navigator.webdriver 默认为 true → 引擎走静态降级;本夹具默认要的是可动画环境 */
|
||
function setWebdriver(value: boolean) {
|
||
Object.defineProperty(navigator, 'webdriver', { configurable: true, get: () => value });
|
||
}
|
||
|
||
function setReduceMotion(value: boolean) {
|
||
const { useReducedMotion } = require('@/hooks/use-reduced-motion');
|
||
(useReducedMotion as jest.Mock).mockReturnValue(value);
|
||
}
|
||
|
||
function setViewport(size: { width: number; height: number }) {
|
||
rectSpy.mockReturnValue({
|
||
...size,
|
||
top: 0,
|
||
left: 0,
|
||
right: size.width,
|
||
bottom: size.height,
|
||
x: 0,
|
||
y: 0,
|
||
toJSON: () => ({}),
|
||
} as DOMRect);
|
||
}
|
||
|
||
/** 画布「可见尺寸」决定回绕边界,与 build() 用的父容器矩形分离,便于构造出界场景 */
|
||
function setCanvasClientBox(width: number, height: number) {
|
||
Object.defineProperty(HTMLCanvasElement.prototype, 'clientWidth', { configurable: true, get: () => width });
|
||
Object.defineProperty(HTMLCanvasElement.prototype, 'clientHeight', { configurable: true, get: () => height });
|
||
}
|
||
|
||
function arcPositions(since = 0): { x: number; y: number }[] {
|
||
return ctxStub.calls
|
||
.slice(since)
|
||
.filter((c) => c.op === 'arc')
|
||
.map((c) => ({ x: Number(c.args[0]), y: Number(c.args[1]) }));
|
||
}
|
||
|
||
function written(prop: string): string[] {
|
||
return ctxStub.styles.filter((s) => s.prop === prop).map((s) => s.value);
|
||
}
|
||
|
||
/** 手动推进 rAF 队列,返回推进的帧数 */
|
||
function runFrames(stamps: number[]): number {
|
||
let done = 0;
|
||
for (const t of stamps) {
|
||
const pending = frameQueue.splice(0, frameQueue.length);
|
||
if (pending.length === 0) break;
|
||
pending.forEach((cb) => cb(t));
|
||
done += 1;
|
||
}
|
||
return done;
|
||
}
|
||
|
||
/** 动画路径下 build() 不直接落笔(paint 只发生在 step 内),推进一帧即可检查绘制结果 */
|
||
function paintOnce() {
|
||
expect(runFrames([16])).toBe(1);
|
||
}
|
||
|
||
beforeEach(() => {
|
||
ctxStub = createCtxStub();
|
||
frameQueue = [];
|
||
getCtxSpy = jest
|
||
.spyOn(HTMLCanvasElement.prototype, 'getContext')
|
||
.mockImplementation((() => ctxStub) as never);
|
||
rectSpy = jest.spyOn(Element.prototype, 'getBoundingClientRect').mockReturnValue({
|
||
...VIEWPORT,
|
||
top: 0,
|
||
left: 0,
|
||
right: VIEWPORT.width,
|
||
bottom: VIEWPORT.height,
|
||
x: 0,
|
||
y: 0,
|
||
toJSON: () => ({}),
|
||
} as DOMRect);
|
||
rafSpy = jest
|
||
.spyOn(window, 'requestAnimationFrame')
|
||
.mockImplementation(((cb: (t: number) => void) => {
|
||
frameQueue.push(cb);
|
||
return frameQueue.length;
|
||
}) as never);
|
||
cafSpy = jest.spyOn(window, 'cancelAnimationFrame').mockImplementation((() => undefined) as never);
|
||
setWebdriver(false);
|
||
setReduceMotion(false);
|
||
setCanvasClientBox(VIEWPORT.width, VIEWPORT.height);
|
||
document.documentElement.style.removeProperty('--color-brand-rgb');
|
||
});
|
||
|
||
afterEach(() => {
|
||
getCtxSpy.mockRestore();
|
||
rectSpy.mockRestore();
|
||
rafSpy.mockRestore();
|
||
cafSpy.mockRestore();
|
||
setWebdriver(originalWebdriver);
|
||
Object.defineProperty(HTMLCanvasElement.prototype, 'clientWidth', { configurable: true, get: () => 0 });
|
||
Object.defineProperty(HTMLCanvasElement.prototype, 'clientHeight', { configurable: true, get: () => 0 });
|
||
document.documentElement.style.removeProperty('--color-brand-rgb');
|
||
delete (globalThis as Record<string, unknown>).ResizeObserver;
|
||
});
|
||
|
||
// ─── 尺寸与密度 ──────────────────────────────────────────────────────────
|
||
|
||
describe('HeroParticleField · 画布尺寸与粒子密度', () => {
|
||
it('sizes the backing store by devicePixelRatio and caps DPR at 2', () => {
|
||
Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 4 });
|
||
const { unmount } = render(<HeroParticleField />);
|
||
const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement;
|
||
expect(canvas.width).toBe(VIEWPORT.width * 2);
|
||
expect(canvas.height).toBe(VIEWPORT.height * 2);
|
||
expect(canvas.style.width).toBe('1200px');
|
||
expect(ctxStub.calls[0]).toEqual({ op: 'setTransform', args: [2, 0, 0, 2, 0, 0] });
|
||
unmount();
|
||
Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 1 });
|
||
});
|
||
|
||
it('keeps a 1x devicePixelRatio untouched', () => {
|
||
Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 1 });
|
||
render(<HeroParticleField />);
|
||
const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement;
|
||
expect(canvas.width).toBe(VIEWPORT.width);
|
||
expect(ctxStub.calls[0]).toEqual({ op: 'setTransform', args: [1, 0, 0, 1, 0, 0] });
|
||
});
|
||
|
||
it('treats a zero devicePixelRatio as 1 instead of collapsing the canvas', () => {
|
||
// 部分宿主在缩放计算前上报 dpr=0:Math.min(0, 2)=0 会把位图缩成 0x0,必须回落到 1
|
||
Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 0 });
|
||
try {
|
||
render(<HeroParticleField />);
|
||
const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement;
|
||
expect(canvas.width).toBe(VIEWPORT.width);
|
||
expect(canvas.style.width).toBe('1200px');
|
||
expect(ctxStub.calls[0]).toEqual({ op: 'setTransform', args: [1, 0, 0, 1, 0, 0] });
|
||
} finally {
|
||
Object.defineProperty(window, 'devicePixelRatio', { configurable: true, get: () => 1 });
|
||
}
|
||
});
|
||
|
||
it('scales particle count with area', () => {
|
||
render(<HeroParticleField />);
|
||
paintOnce();
|
||
// 1200x700 / 26000 ≈ 32
|
||
expect(arcPositions()).toHaveLength(32);
|
||
});
|
||
|
||
it('caps particle count at 56 on a very large viewport', () => {
|
||
setViewport({ width: 4000, height: 4000 });
|
||
render(<HeroParticleField />);
|
||
paintOnce();
|
||
expect(arcPositions()).toHaveLength(56);
|
||
});
|
||
|
||
it('draws nothing extra when the container has zero area', () => {
|
||
setViewport({ width: 0, height: 0 });
|
||
render(<HeroParticleField />);
|
||
paintOnce();
|
||
const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement;
|
||
// 面积为 0 时不产生粒子,但画布仍保留 1px 下限(避免 canvas 尺寸非法)
|
||
expect(canvas.width).toBe(1);
|
||
expect(arcPositions()).toHaveLength(0);
|
||
expect(written('fillStyle')).toHaveLength(0);
|
||
});
|
||
});
|
||
|
||
// ─── 变体绘制 ────────────────────────────────────────────────────────────
|
||
|
||
describe('HeroParticleField · 变体绘制', () => {
|
||
const renderVariant = (variant: HeroVariant, dark = false) => {
|
||
const view = render(<HeroParticleField variant={variant} dark={dark} />);
|
||
paintOnce();
|
||
return view;
|
||
};
|
||
|
||
it('drift paints nodes only — no links, no streams, no glow', () => {
|
||
renderVariant('drift');
|
||
expect(ctxStub.gradients).toHaveLength(0);
|
||
expect(ctxStub.calls.filter((c) => c.op === 'stroke')).toHaveLength(0);
|
||
expect(written('shadowColor')).toHaveLength(0);
|
||
expect(written('fillStyle').length).toBeGreaterThan(0);
|
||
});
|
||
|
||
it('grid draws thin ink links on a light background', () => {
|
||
renderVariant('grid');
|
||
expect(written('strokeStyle')).toContain('rgba(10,14,20,1)');
|
||
expect(written('shadowColor')).toHaveLength(0);
|
||
});
|
||
|
||
it('network draws white links and brand-red glow only for the bright nodes on dark', () => {
|
||
renderVariant('network', true);
|
||
expect(written('strokeStyle')).toContain('rgba(255,255,255,1)');
|
||
expect(written('shadowColor')).toContain('rgba(196,30,58,0.9)');
|
||
expect(written('shadowBlur')).toContain('8');
|
||
});
|
||
|
||
it('spotlight combines links with glow', () => {
|
||
renderVariant('spotlight', true);
|
||
expect(ctxStub.calls.filter((c) => c.op === 'stroke').length).toBeGreaterThan(0);
|
||
expect(written('shadowColor')).toContain('rgba(196,30,58,0.9)');
|
||
});
|
||
|
||
it('constellation adds vertical data streams and dim secondary nodes', () => {
|
||
renderVariant('constellation', true);
|
||
// 16 条竖向数据流,各用一条线性渐变
|
||
expect(ctxStub.gradients).toHaveLength(16);
|
||
expect(ctxStub.gradients[0]!.addColorStop).toHaveBeenCalledTimes(3);
|
||
const fills = written('fillStyle');
|
||
expect(fills.some((f) => f.startsWith('rgba(180,190,205'))).toBe(true); // 暗白次级节点
|
||
expect(fills.some((f) => f.startsWith('rgba(196, 30, 58'))).toBe(true); // 品牌红主节点
|
||
// 次级节点半径收缩到 0.7 倍,且不做 dim 的每 4 个一取的规则会被固定种子复现
|
||
const dimCount = ctxStub.calls.filter((c) => c.op === 'arc').length;
|
||
expect(dimCount).toBe(32);
|
||
});
|
||
|
||
it('uses the cool-grey dim node on a light constellation too', () => {
|
||
renderVariant('constellation', false);
|
||
expect(written('fillStyle').some((f) => f.startsWith('rgba(100,116,139'))).toBe(true);
|
||
expect(written('shadowColor')).toHaveLength(0); // 浅底不辉光
|
||
});
|
||
|
||
it('re-derives the variant when the prop changes', () => {
|
||
const { rerender } = render(<HeroParticleField variant="drift" />);
|
||
paintOnce();
|
||
expect(ctxStub.gradients).toHaveLength(0);
|
||
const before = ctxStub.calls.length;
|
||
rerender(<HeroParticleField variant="constellation" />);
|
||
paintOnce();
|
||
expect(screen.getByTestId('hero-particle-field')).toHaveAttribute('data-variant', 'constellation');
|
||
expect(ctxStub.calls.length).toBeGreaterThan(before);
|
||
expect(ctxStub.gradients).toHaveLength(16);
|
||
});
|
||
});
|
||
|
||
// ─── 品牌色读取 ──────────────────────────────────────────────────────────
|
||
|
||
describe('HeroParticleField · 品牌红取值', () => {
|
||
it('reads --color-brand-rgb from the document root', () => {
|
||
document.documentElement.style.setProperty('--color-brand-rgb', '12 200 40');
|
||
render(<HeroParticleField />);
|
||
paintOnce();
|
||
expect(written('fillStyle')[0]).toContain('rgba(12, 200, 40,');
|
||
});
|
||
|
||
it.each([
|
||
['malformed tokens', 'a b c'],
|
||
['a partial triple', '12 34'],
|
||
])('falls back to the literal brand red for %s', (_label, raw) => {
|
||
document.documentElement.style.setProperty('--color-brand-rgb', raw);
|
||
render(<HeroParticleField />);
|
||
paintOnce();
|
||
expect(written('fillStyle')[0]).toContain('rgba(196, 30, 58,');
|
||
});
|
||
|
||
it('falls back when the token is not declared at all', () => {
|
||
render(<HeroParticleField />);
|
||
paintOnce();
|
||
expect(written('fillStyle')[0]).toContain('rgba(196, 30, 58,');
|
||
});
|
||
});
|
||
|
||
// ─── 动画循环 ────────────────────────────────────────────────────────────
|
||
|
||
describe('HeroParticleField · 循环与降级', () => {
|
||
it('drives a continuous rAF loop that keeps every node inside the wrap box', () => {
|
||
setCanvasClientBox(8, 8); // 视口远小于初始分布 → 第一帧即触发回绕
|
||
render(<HeroParticleField />);
|
||
expect(rafSpy).toHaveBeenCalledTimes(1);
|
||
const frames = runFrames([16, 32, 48, 64, 96, 120, 160, 200]);
|
||
expect(frames).toBeGreaterThan(1);
|
||
|
||
const positions = arcPositions();
|
||
const xs = positions.map((p) => p.x);
|
||
const ys = positions.map((p) => p.y);
|
||
expect(positions.length).toBe(32 * frames);
|
||
expect(Math.min(...xs)).toBeGreaterThanOrEqual(-3);
|
||
expect(Math.max(...xs)).toBeLessThanOrEqual(11);
|
||
expect(Math.min(...ys)).toBeGreaterThanOrEqual(-3);
|
||
expect(Math.max(...ys)).toBeLessThanOrEqual(11);
|
||
// 两个方向都真的发生了回绕:右出界 → 左侧 -3 入场,左出界 → 右侧 w+3 入场
|
||
expect(xs).toContain(-3);
|
||
expect(xs).toContain(11);
|
||
expect(ys).toContain(-3);
|
||
expect(ys).toContain(11);
|
||
});
|
||
|
||
it('falls back to the backing-store box while the canvas has no layout size', () => {
|
||
// 首帧尚未排版时 clientWidth/Height 会是 0:回绕与淡出必须改用位图尺寸,而不是被 0x0 挤到边界
|
||
setCanvasClientBox(0, 0);
|
||
render(<HeroParticleField />);
|
||
paintOnce();
|
||
const positions = arcPositions();
|
||
const xs = positions.map((p) => p.x);
|
||
const ys = positions.map((p) => p.y);
|
||
expect(positions).toHaveLength(32);
|
||
expect(Math.max(...xs) - Math.min(...xs)).toBeGreaterThan(600);
|
||
expect(Math.max(...ys) - Math.min(...ys)).toBeGreaterThan(300);
|
||
expect(Math.max(...xs)).toBeLessThanOrEqual(VIEWPORT.width + 3);
|
||
expect(Math.max(...ys)).toBeLessThanOrEqual(VIEWPORT.height + 3);
|
||
});
|
||
|
||
it('cancels the scheduled frame on unmount', () => {
|
||
const { unmount } = render(<HeroParticleField />);
|
||
runFrames([16]);
|
||
unmount();
|
||
expect(cafSpy).toHaveBeenCalled();
|
||
});
|
||
|
||
it('paints a single static frame and never schedules rAF under reduced motion', () => {
|
||
setReduceMotion(true);
|
||
render(<HeroParticleField />);
|
||
expect(rafSpy).not.toHaveBeenCalled();
|
||
expect(ctxStub.calls.filter((c) => c.op === 'fill')).toHaveLength(32);
|
||
setReduceMotion(false);
|
||
});
|
||
|
||
it('paints a single static frame in automated browsers (navigator.webdriver)', () => {
|
||
setWebdriver(true);
|
||
render(<HeroParticleField />);
|
||
expect(rafSpy).not.toHaveBeenCalled();
|
||
expect(arcPositions()).toHaveLength(32);
|
||
// 静态帧仍要落笔:边缘淡出后的透明度写入了 fillStyle
|
||
expect(written('fillStyle').length).toBeGreaterThan(0);
|
||
});
|
||
|
||
it('degrades to a static frame when requestAnimationFrame is unavailable', () => {
|
||
const savedRaf = window.requestAnimationFrame;
|
||
// @ts-expect-error 运行期删除,模拟无 rAF 的老宿主
|
||
delete window.requestAnimationFrame;
|
||
try {
|
||
render(<HeroParticleField />);
|
||
expect(arcPositions()).toHaveLength(32);
|
||
expect(rafSpy).not.toHaveBeenCalled();
|
||
} finally {
|
||
// `writable` 必须显式给出:defineProperty 的默认值是 false,缺省会把它变成只读属性,
|
||
// 随后 afterEach 里 rafSpy.mockRestore() 的赋值就会抛
|
||
// "Cannot assign to read only property 'requestAnimationFrame'",整套件判为 failed to run。
|
||
Object.defineProperty(window, 'requestAnimationFrame', {
|
||
configurable: true,
|
||
writable: true,
|
||
value: savedRaf,
|
||
});
|
||
}
|
||
});
|
||
|
||
it('stops when the tab is hidden and restarts when it becomes visible', () => {
|
||
render(<HeroParticleField />);
|
||
const rafCallsBefore = rafSpy.mock.calls.length;
|
||
const visibility = Object.getOwnPropertyDescriptor(Document.prototype, 'visibilityState')
|
||
?? Object.getOwnPropertyDescriptor(document, 'visibilityState');
|
||
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' });
|
||
document.dispatchEvent(new Event('visibilitychange'));
|
||
expect(cafSpy).toHaveBeenCalled();
|
||
expect(rafSpy.mock.calls.length).toBe(rafCallsBefore);
|
||
|
||
Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'visible' });
|
||
document.dispatchEvent(new Event('visibilitychange'));
|
||
expect(rafSpy.mock.calls.length).toBeGreaterThan(rafCallsBefore);
|
||
if (visibility) Object.defineProperty(document, 'visibilityState', visibility);
|
||
});
|
||
|
||
it('still runs the loop on hosts without IntersectionObserver and unmounts cleanly', () => {
|
||
// 老宿主缺 IO:引擎要直接按挂载即起跑,卸载时的 io?.disconnect() 也不能抛错
|
||
const savedIO = (globalThis as Record<string, unknown>).IntersectionObserver;
|
||
delete (globalThis as Record<string, unknown>).IntersectionObserver;
|
||
try {
|
||
const { unmount } = render(<HeroParticleField />);
|
||
expect(rafSpy).toHaveBeenCalledTimes(1);
|
||
paintOnce();
|
||
expect(arcPositions()).toHaveLength(32);
|
||
expect(() => unmount()).not.toThrow();
|
||
expect(cafSpy).toHaveBeenCalled();
|
||
} finally {
|
||
(globalThis as Record<string, unknown>).IntersectionObserver = savedIO;
|
||
}
|
||
});
|
||
|
||
it('rebuilds and repaints through ResizeObserver when the host provides one', () => {
|
||
const observers: Array<{ cb: () => void; targets: Element[]; disconnected: boolean }> = [];
|
||
class MockResizeObserver {
|
||
cb: () => void;
|
||
targets: Element[] = [];
|
||
disconnected = false;
|
||
constructor(cb: () => void) {
|
||
this.cb = cb;
|
||
observers.push(this);
|
||
}
|
||
observe(el: Element) {
|
||
this.targets.push(el);
|
||
}
|
||
unobserve() {}
|
||
disconnect() {
|
||
this.disconnected = true;
|
||
}
|
||
}
|
||
(globalThis as Record<string, unknown>).ResizeObserver = MockResizeObserver;
|
||
|
||
render(<HeroParticleField />);
|
||
const canvas = screen.getByTestId('hero-particle-field') as HTMLCanvasElement;
|
||
expect(canvas.width).toBe(1200);
|
||
const observer = observers[0];
|
||
expect(observer?.targets).toHaveLength(1);
|
||
|
||
setViewport({ width: 800, height: 600 });
|
||
observer!.cb();
|
||
// 重建:位图尺寸与变换矩阵按新容器重排(800x600 / 26000 ≈ 18 个粒子)
|
||
expect(canvas.width).toBe(800);
|
||
expect(canvas.height).toBe(600);
|
||
expect(ctxStub.calls.filter((c) => c.op === 'setTransform')).toHaveLength(2);
|
||
runFrames([16]);
|
||
expect(arcPositions()).toHaveLength(18);
|
||
});
|
||
|
||
it('disconnects the observers on unmount', () => {
|
||
const observers: Array<{ disconnected: boolean }> = [];
|
||
class MockResizeObserver {
|
||
disconnected = false;
|
||
constructor(cb: () => void) {
|
||
void cb;
|
||
observers.push(this);
|
||
}
|
||
observe() {}
|
||
unobserve() {}
|
||
disconnect() {
|
||
this.disconnected = true;
|
||
}
|
||
}
|
||
(globalThis as Record<string, unknown>).ResizeObserver = MockResizeObserver;
|
||
const { unmount } = render(<HeroParticleField />);
|
||
unmount();
|
||
expect(observers[0]?.disconnected).toBe(true);
|
||
});
|
||
|
||
it('appends a custom class to the canvas layer', () => {
|
||
render(<HeroParticleField className="hero-overlay" />);
|
||
const canvas = screen.getByTestId('hero-particle-field');
|
||
expect(canvas.className).toContain('hero-overlay');
|
||
expect(canvas.className).toContain('pointer-events-none');
|
||
});
|
||
});
|