AstrBot-Desktop/src/test/setup.ts
YokiiroBW 124cf32fa2 fix(ui): release tauri event listeners on unmount
All four listen() call sites assigned the resolved unregister function
unconditionally. When the effect was cleaned up before the promise
settled, that assignment landed on a dead closure and the listener was
never unregistered. React StrictMode mounts, cleans up and mounts again,
so the first listener leaked on every development mount. In ChatPanel
that meant applyRuntimeEvents ran twice per event and, because a delta
is appended to the existing content, every character of a streamed reply
was doubled.

Track whether the effect is still live and unregister immediately when
the promise settles late. Each site also gains a catch, since these were
all bare void listen(...).then(...) chains — a rejected listen, such as
the missing desktop-pet capability, became an unhandled rejection rather
than anything observable.

The listener mock in src/test/setup.ts resolved eagerly, which made the
race impossible to express. Replace it with a controllable double in
src/test/tauriEvent.ts that defers resolution until the test asks for
it, tracks each registration separately, and only dispatches to handlers
that have not been unregistered. The registry is plain module state, so
setup.ts resets it after each test.

ChatPanel had no test file; this adds one. Both new tests were checked
against a mutation restoring the old assignment, and both fail under it.

Refs: F-15 (audit P1-10).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 00:23:42 +08:00

19 行
534 B
TypeScript

import "@testing-library/jest-dom/vitest";
import { vi } from "vitest";
vi.mock("@tauri-apps/api/event", async () => {
const { listenMock } = await import("./tauriEvent");
return { listen: listenMock };
});
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
import { resetTauriEvent } from "./tauriEvent";
afterEach(() => {
cleanup();
// The registry is plain module state, so `clearMocks` does not reach it.
// Without this, listeners leak across test files.
resetTauriEvent();
});