test(sidebar-crash): 修掉 afterEach 不清挂载导致的定时器泄漏(既有 flake,CI 间歇红)

现象:`ci` 的 Test 步骤红,但日志里 173 files / 1962 tests **全部通过**,只有一个未捕获错误:
`ReferenceError: window is not defined`,栈落在 src/client/session-phase.ts:44 的 setPhase。

根因:本 spec 的 afterEach 用 document.body.innerHTML = '' **直接清 DOM,从不 root.unmount()**
→ 所有 effect 的 cleanup 都不执行 → 组件里的 setInterval 全部继续armed(实测每个用例泄漏
**5 个**),活过 jsdom 销毁;之后轮询落到 catch 分支调 setPhase,React 去读已不存在的 window。
是否触发取决于调度时序(本次 ubuntu runner 明显更慢:49s vs 21s),所以同树另一次运行全绿。

修法(源头在 harness,不在产品代码):
① mountSidebar 把 unmount 收进 mountedRoots(并做成幂等,显式 unmount 过的用例不会被二次卸载);
② afterEach **先卸载**(这正是跑 cleanup 的那一步),再清 body;
③ 新增不变量断言:afterEach 里若仍有存活 interval 即失败 —— 定时器不得活过一个用例。

判别性验证:把 ② 的卸载去掉、保留守卫与断言 → **4 个用例红**
(`every interval started by a test must be cleared before it ends: expected 5 to be +0`);
恢复后 6/6 绿,该 spec 连跑 8 次全绿。另加一条「先证明轮询真的被 armed」的用例,避免守卫空转。

全量:173 files / 1963 passed | 13 skipped(新增 1 例),typecheck 0,eslint 0。
This commit is contained in:
Menghuan1918 committed 2026-10-05 11:32:16 +08:00
1 parent d51a46075d
commit 38ceecb051
1 file changed
+63 -8
+63 -8
View File
@@ -57,12 +57,37 @@ interface MountedSidebar {
unmount: () => void
}
/** Roots still mounted when a test ends. `afterEach` unmounts them: wiping the
* DOM without unmounting leaves every effect cleanup un-run, and the 1s
* `session.phase` poller in `session-phase.ts` then outlives the test — it
* fires after jsdom is gone, React reads a missing `window` and the whole run
* is red on `Errors 1` even though every test passed. */
const mountedRoots: Array<() => void> = []
/** Intervals created while a test runs. `session-phase.ts` polls through
* `setInterval`; a live id here after the roots are unmounted means some
* effect leaked a timer (see `mountedRoots`). */
const liveIntervals = new Set<ReturnType<typeof setInterval>>()
/** Mount the real Sidebar shell against a minimal context (real store + service). */
/** Unique per-test session ids (see the comment inside). */
let sessionSeq = 0
function mountSidebar(): MountedSidebar {
vi.stubGlobal('WebSocket', FakeWebSocket)
// The real timers, wrapped so `afterEach` can prove nothing outlived the
// test (vi.unstubAllGlobals restores both).
const realSetInterval = globalThis.setInterval
const realClearInterval = globalThis.clearInterval
vi.stubGlobal('setInterval', ((handler: never, timeout?: number) => {
const id = realSetInterval(handler, timeout)
liveIntervals.add(id)
return id
}) as never)
vi.stubGlobal('clearInterval', ((id: never) => {
liveIntervals.delete(id)
realClearInterval(id)
}) as never)
const container = document.createElement('div')
document.body.append(container)
const store = createSidebarStore()
@@ -96,18 +121,30 @@ function mountSidebar(): MountedSidebar {
}
const root: Root = createRoot(container)
act(() => { root.render(createElement(Sidebar, { ctx: ctx as never, store })) })
return {
container,
store,
service,
unmount: () => {
act(() => { root.unmount() })
container.remove()
},
// Idempotent: a test may unmount explicitly, and afterEach unmounts whatever
// is left (calling React's unmount twice throws).
let unmounted = false
const unmount = (): void => {
if (unmounted) return
unmounted = true
act(() => { root.unmount() })
container.remove()
}
mountedRoots.push(unmount)
return { container, store, service, unmount }
}
afterEach(() => {
// Unmount FIRST: that is what runs the effects' cleanups, and the cleanups
// are what clear the pollers. Wiping the DOM instead (the old harness) left
// them armed and reddened CI with `window is not defined`.
for (const unmount of mountedRoots.splice(0).reverse()) unmount()
const leaked = liveIntervals.size
liveIntervals.clear()
expect(
leaked,
'every interval started by a test must be cleared before it ends — an armed one fires after jsdom is torn down',
).toBe(0)
document.body.innerHTML = ''
// Belt and braces: drop any persisted layout a pending 200ms debounce
// write left behind between tests (unique session ids already isolate).
@@ -115,6 +152,24 @@ afterEach(() => {
vi.unstubAllGlobals()
})
describe('test harness', () => {
// The leak guard itself lives in `afterEach` (no interval may outlive a
// test). A poll that never settles keeps the 1s `session.phase` interval
// armed from mount to the end of the test — which is exactly the state the
// old harness (wipe the DOM, never unmount) leaked past teardown: the timer
// fired after jsdom was gone, React read a missing `window`, and an
// all-green run went red on `Errors 1`. The assertion below proves the
// armed state was really reached, so this test cannot pass vacuously.
it('arms the session-phase poller, so afterEach has something to clear', () => {
vi.stubGlobal('fetch', () => new Promise(() => {}))
mountSidebar()
expect(
liveIntervals.size,
'the hanging route must leave the poller armed',
).toBeGreaterThan(0)
})
})
describe('layout-push variable cleanup', () => {
it('clears --dsh-sidebar-height when the sidebar unmounts (and never pushes a width)', () => {
const { unmount } = mountSidebar()