import { test } from 'node:test' import assert from 'node:assert/strict' import { useHistoryPolling } from '../src/shared/composables/useHistoryPolling.ts' import type { CategorizedTimers } from '../src/shared/utils/categorized-timers.ts' function fakeTimers() { const scheduled: Array<{ category: string; id: number; delay: number; run: () => void }> = [] const cleared: number[] = [] let seq = 0 const timers = { setTimeout(category: string, handler: () => void, delayMs: number) { const id = ++seq scheduled.push({ category, id, delay: delayMs, run: handler }) return id }, clearTimer(_category: string, id: number | null | undefined) { if (id != null) cleared.push(id) }, } return { timers: timers as unknown as CategorizedTimers, scheduled, cleared } } test('shouldPoll 为 false 时不排定时器', () => { const { timers, scheduled } = fakeTimers() const p = useHistoryPolling({ timers, isDisposed: () => false, shouldPoll: () => false, refresh: async () => {}, intervalMs: () => 40, }) p.start() assert.equal(scheduled.length, 0) }) test('按传入间隔排定 history-poll,触发后刷新并续排', async () => { const { timers, scheduled } = fakeTimers() let calls = 0 const p = useHistoryPolling({ timers, isDisposed: () => false, shouldPoll: () => true, refresh: async () => { calls += 1 }, intervalMs: () => 40, }) p.start() assert.equal(scheduled.length, 1) assert.equal(scheduled[0].category, 'history-poll') assert.equal(scheduled[0].delay, 40) await scheduled[0].run() assert.equal(calls, 1) assert.equal(scheduled.length, 2) assert.equal(scheduled[1].delay, 40) }) test('stop 清除已排定的定时器', () => { const { timers, scheduled, cleared } = fakeTimers() const p = useHistoryPolling({ timers, isDisposed: () => false, shouldPoll: () => true, refresh: async () => {}, intervalMs: () => 40, }) p.start() p.stop() assert.equal(scheduled.length, 1) assert.deepEqual(cleared, [scheduled[0].id]) }) test('已卸载时触发不再刷新也不续排', async () => { const { timers, scheduled } = fakeTimers() let disposed = false let calls = 0 const p = useHistoryPolling({ timers, isDisposed: () => disposed, shouldPoll: () => true, refresh: async () => { calls += 1 }, intervalMs: () => 40, }) p.start() disposed = true await scheduled[0].run() assert.equal(calls, 0) assert.equal(scheduled.length, 1) }) test('刷新后队列已空则不再续排', async () => { const { timers, scheduled } = fakeTimers() let work = true const p = useHistoryPolling({ timers, isDisposed: () => false, shouldPoll: () => work, refresh: async () => { work = false }, intervalMs: () => 40, }) p.start() await scheduled[0].run() assert.equal(scheduled.length, 1) })