import { afterEach, describe, expect, it, vi } from 'vitest' const uiHarness = vi.hoisted(() => { interface RefSlot { kind: 'ref' ref: { current: unknown } } interface EffectSlot { kind: 'effect' deps: readonly unknown[] | undefined create: () => void | (() => void) cleanup: (() => void) | undefined } type Slot = RefSlot | EffectSlot const slots: Slot[] = [] const pendingEffects: number[] = [] let cursor = 0 function depsChanged( prev: readonly unknown[] | undefined, next: readonly unknown[] | undefined, ): boolean { if (prev === undefined || next === undefined) return true if (prev.length !== next.length) return true for (let i = 0; i < next.length; i += 1) { if (!Object.is(prev[i], next[i])) return true } return false } function reset(): void { for (const slot of slots) { if (slot.kind === 'effect' && slot.cleanup) { slot.cleanup() } } slots.length = 0 pendingEffects.length = 0 cursor = 0 } function renderComponent(fn: () => unknown): void { cursor = 0 fn() const indices = pendingEffects.splice(0) for (const idx of indices) { const slot = slots[idx] if (!slot || slot.kind !== 'effect') continue if (slot.cleanup) { slot.cleanup() slot.cleanup = undefined } const cleanup = slot.create() slot.cleanup = typeof cleanup === 'function' ? cleanup : undefined } } function getRef(index = 0): { current: T } { const slot = slots[index] if (!slot || slot.kind !== 'ref') { throw new Error(`Expected ref slot at index ${index}`) } return slot.ref as { current: T } } let seededCanvas: unknown = null function setCanvasSeed(canvas: unknown): void { seededCanvas = canvas } const reactMock = { useRef(initial: T): { current: T } { const idx = cursor++ const existing = slots[idx] if (existing && existing.kind === 'ref') { return existing.ref as { current: T } } const value = initial === null && seededCanvas !== null ? (seededCanvas as T) : initial const slot: RefSlot = { kind: 'ref', ref: { current: value } } slots[idx] = slot return slot.ref as { current: T } }, useEffect(create: () => void | (() => void), deps?: readonly unknown[]): void { const idx = cursor++ const existing = slots[idx] if (!existing || existing.kind !== 'effect') { slots[idx] = { kind: 'effect', deps, create, cleanup: undefined } pendingEffects.push(idx) return } if (depsChanged(existing.deps, deps)) { existing.deps = deps existing.create = create pendingEffects.push(idx) } }, } return { reset, renderComponent, getRef, setCanvasSeed, reactMock } }) vi.mock('react', () => ({ ...uiHarness.reactMock, default: uiHarness.reactMock, })) vi.mock('react/jsx-runtime', () => ({ Fragment: 'Fragment', jsx: (type: unknown, props: unknown) => ({ type, props }), jsxs: (type: unknown, props: unknown) => ({ type, props }), })) vi.mock('react/jsx-dev-runtime', () => ({ Fragment: 'Fragment', jsxDEV: (type: unknown, props: unknown) => ({ type, props }), })) import { AudioVisualizerBar } from '../src/components/ds/AudioVisualizerBar' import { GradientWave } from '../src/components/ds/GradientWave' import { clampAudioLevel, stepSmoothedAudioLevel } from '../src/components/ds/wave-math' interface CanvasProbe { gradientCreates: number roundRectArgs: number[][] stepFrames: (count: number) => void restore: () => void } function installCanvasGlobals(width = 240, height = 48): CanvasProbe { const roundRectArgs: number[][] = [] let gradientCreates = 0 let rafCounter = 0 const rafQueue = new Map() const fakeCtx = { setTransform: vi.fn(), clearRect: vi.fn(), beginPath: vi.fn(), fill: vi.fn(), roundRect: (...args: number[]) => { roundRectArgs.push(args) }, createLinearGradient: () => { gradientCreates += 1 return { addColorStop: vi.fn() } }, fillStyle: '', shadowBlur: 0, shadowColor: '', } const fakeCanvas = { clientWidth: width, clientHeight: height, width: 0, height: 0, getContext: () => fakeCtx, } class MockResizeObserver { observe(): void {} disconnect(): void {} } vi.stubGlobal('ResizeObserver', MockResizeObserver) vi.stubGlobal('window', { devicePixelRatio: 1 }) vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { rafCounter += 1 rafQueue.set(rafCounter, cb) return rafCounter }) vi.stubGlobal('cancelAnimationFrame', (id: number) => { rafQueue.delete(id) }) // 최초 렌더 후 canvasRef 에 가짜 캔버스를 주입하기 위해 hook 슬롯에 접근할 수 있도록 헬퍼 반환 ;(installCanvasGlobals as { lastCanvas?: unknown }).lastCanvas = fakeCanvas return { get gradientCreates() { return gradientCreates }, roundRectArgs, stepFrames(count: number) { for (let i = 0; i < count; i += 1) { const next = rafQueue.entries().next() if (next.done) break const [id, cb] = next.value rafQueue.delete(id) cb(i * 16) } }, restore() { vi.unstubAllGlobals() }, } } describe('AudioVisualizerBar & GradientWave 캔버스 안전성과 성능 계약', () => { afterEach(() => { uiHarness.setCanvasSeed(null) uiHarness.reset() vi.unstubAllGlobals() }) it('AudioVisualizerBar_연속프레임렌더시_그라디언트를매프레임재생성하지않고NaN레벨에서도유한한높이를그린다', () => { const probe = installCanvasGlobals(240, 48) const fakeCanvas = (installCanvasGlobals as { lastCanvas?: unknown }).lastCanvas uiHarness.setCanvasSeed(fakeCanvas) uiHarness.renderComponent(() => AudioVisualizerBar({ audioLevel: Number.NaN, bars: 12 })) probe.stepFrames(10) expect(probe.gradientCreates).toBe(1) expect(probe.roundRectArgs.length).toBe(120) const hasNonFinite = probe.roundRectArgs.some((args) => args.some((n) => !Number.isFinite(n))) expect(hasNonFinite).toBe(false) // NaN 이후 유효 레벨이 들어와도 smoothedRef가 회복되어 정상 동작해야 한다 uiHarness.renderComponent(() => AudioVisualizerBar({ audioLevel: 0.8, bars: 12 })) probe.roundRectArgs.length = 0 probe.stepFrames(2) const recoveredHasNaN = probe.roundRectArgs.some((args) => args.some((n) => !Number.isFinite(n))) expect(recoveredHasNaN).toBe(false) }) it('GradientWave_NaN및음수오디오레벨에서도_안전하고유한한좌표만그린다', () => { const probe = installCanvasGlobals(180, 40) const fakeCanvas = (installCanvasGlobals as { lastCanvas?: unknown }).lastCanvas uiHarness.setCanvasSeed(fakeCanvas) uiHarness.renderComponent(() => GradientWave({ audioLevel: Number.NaN })) probe.stepFrames(5) const hasNaN = probe.roundRectArgs.some((args) => args.some((n) => !Number.isFinite(n))) expect(hasNaN).toBe(false) expect(probe.roundRectArgs.length).toBeGreaterThan(0) // barWidth + barGap <= 0 이면 무한 루프나 음수 계산 없이 프레임을 건너뛴다 uiHarness.reset() probe.roundRectArgs.length = 0 uiHarness.setCanvasSeed(fakeCanvas) uiHarness.renderComponent(() => GradientWave({ audioLevel: 0.5, barWidth: 0, barGap: 0 })) probe.stepFrames(2) expect(probe.roundRectArgs).toEqual([]) }) it('waveMath_음수및NaN입력_클램프와스무딩상태회복을보장한다', () => { expect(clampAudioLevel(-0.5)).toBe(0) expect(clampAudioLevel(Number.NaN)).toBe(0) expect(clampAudioLevel(1.8)).toBe(1) expect(stepSmoothedAudioLevel(Number.NaN, 0.5, 0.5, 0.1)).toBe(0.25) }) })