Skip to content

Commit e8a0e10

Browse files
authored
fix(browser-sdk): clean up Preact roots before test teardown (#745)
## Root cause Both #739 and #742 were ejected from the merge queue after all 205 browser assertions passed: a delayed Preact toolbar render accessed sessionStorage after jsdom teardown. client.stop() does not unmount the UI; removing DOM nodes alone does not cancel Preact work. ## Fix - Unmount feedback and toolbar shadow-root trees before removing their hosts in shared afterEach cleanup. - Return the toolbar flagsUpdated unsubscribe function from its effect. - Remove the earlier usage.test.ts toolbar mock: tests now exercise the real toolbar. - Add two deterministic regressions covering delayed effects and already-queued renders after browser globals disappear. Omitting the unmount makes both fail with the exact ReferenceError. ## Validation - Unmodified main: reproduced the exact sessionStorage rejection in 5 of 40 complete browser-suite runs in a local Linux container (Node 24.13.0, 2 CPUs, CI=true). - Fixed code: **0 failures in 40 complete browser-suite runs** in the same Linux container, with the usage-test toolbar mock removed. Every run exited 0. - Both GitHub Build & Test checks passed. - The two deterministic tests pass with unmounting, and both fail with the exact `ReferenceError: sessionStorage is not defined` when `render(null, host.shadowRoot)` is omitted (even when the host DOM node is removed). - Local reproduction logs: `/tmp/reflag-flake-linux/repro-baseline/{1..40}.log` and `/tmp/reflag-flake-linux/repro-fixed/{1..40}.log`; fixed exit codes are in `repro-fixed/results.txt`. - Reproduction environment: `node:24.13.0-bookworm`, Docker `--cpus=2`, immutable root install, then repeatedly run `CI=true yarn vitest run --reporter=default` from `packages/browser-sdk`. Native macOS runs did not reproduce the exact error, so the before/after counts above are exclusively Linux. - Full uncached build and all nine workspace test:ci targets passed locally, including Playwright. - Formatting and lint passed (existing Next-generated triple-slash warning only). Follow-up: once merged, requeue #739 and #742.
1 parent 8e7b257 commit e8a0e10

6 files changed

Lines changed: 113 additions & 4 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@reflag/browser-sdk": patch
3+
---
4+
5+
Unsubscribe toolbar flag listeners when the toolbar is unmounted or switches clients.

‎packages/browser-sdk/src/toolbar/Toolbar.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ export default function Toolbar({
6868

6969
useEffect(() => {
7070
updateFlags();
71-
reflagClient.on("flagsUpdated", updateFlags);
71+
return reflagClient.on("flagsUpdated", updateFlags);
7272
}, [reflagClient, updateFlags]);
7373

7474
const [search, setSearch] = useState<string | null>(null);
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import { options } from "preact";
2+
import { afterEach, beforeEach, expect, test, vi } from "vitest";
3+
4+
import { ReflagClient } from "../src/client";
5+
import { showToolbarToggle } from "../src/toolbar";
6+
import { toolbarContainerId } from "../src/ui/constants";
7+
import { cleanupUi } from "./cleanupUi";
8+
9+
let effects: (() => void)[];
10+
let renders: (() => void)[];
11+
const originalRaf = options.requestAnimationFrame;
12+
const originalDebounce = options.debounceRendering;
13+
14+
beforeEach(() => {
15+
effects = [];
16+
renders = [];
17+
// Hold the actual Preact callbacks so teardown timing is deterministic.
18+
options.requestAnimationFrame = (callback) => effects.push(callback);
19+
options.debounceRendering = (callback) => renders.push(callback);
20+
});
21+
22+
function drainCallbacks() {
23+
while (effects.length || renders.length) {
24+
effects.shift()?.();
25+
renders.shift()?.();
26+
}
27+
}
28+
29+
function withoutSessionStorage(callback: () => void) {
30+
const descriptor = Object.getOwnPropertyDescriptor(
31+
globalThis,
32+
"sessionStorage",
33+
)!;
34+
Reflect.deleteProperty(globalThis, "sessionStorage");
35+
try {
36+
callback();
37+
} finally {
38+
Object.defineProperty(globalThis, "sessionStorage", descriptor);
39+
}
40+
}
41+
42+
function mountToolbar() {
43+
const client = new ReflagClient({
44+
publishableKey: "test-key",
45+
offline: true,
46+
toolbar: false,
47+
});
48+
const unsubscribe = vi.fn();
49+
const on = vi.spyOn(client, "on").mockReturnValue(unsubscribe);
50+
showToolbarToggle({ reflagClient: client });
51+
expect(document.getElementById(toolbarContainerId)).not.toBeNull();
52+
return { on, unsubscribe };
53+
}
54+
55+
afterEach(() => {
56+
cleanupUi();
57+
drainCallbacks();
58+
options.requestAnimationFrame = originalRaf;
59+
options.debounceRendering = originalDebounce;
60+
vi.restoreAllMocks();
61+
});
62+
63+
test("unmounts before a delayed toolbar effect can run after jsdom teardown", () => {
64+
const { on } = mountToolbar();
65+
expect(effects.length).toBeGreaterThan(0);
66+
67+
cleanupUi();
68+
69+
withoutSessionStorage(() => {
70+
expect(drainCallbacks).not.toThrow();
71+
});
72+
expect(on).not.toHaveBeenCalled();
73+
expect(document.getElementById(toolbarContainerId)).toBeNull();
74+
});
75+
76+
test("cancels queued toolbar renders and unsubscribes mounted effects", () => {
77+
const { unsubscribe } = mountToolbar();
78+
// Run useEffect: updateFlags queues a render and subscribes to flagsUpdated.
79+
while (effects.length) effects.shift()!();
80+
expect(renders.length).toBeGreaterThan(0);
81+
82+
cleanupUi();
83+
84+
withoutSessionStorage(() => {
85+
expect(drainCallbacks).not.toThrow();
86+
});
87+
expect(unsubscribe).toHaveBeenCalledOnce();
88+
expect(document.getElementById(toolbarContainerId)).toBeNull();
89+
});
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { render } from "preact";
2+
3+
import { feedbackContainerId, toolbarContainerId } from "../src/ui/constants";
4+
5+
/** Unmount Preact before removing its hosts or tearing down jsdom globals. */
6+
export function cleanupUi() {
7+
if (typeof document === "undefined") return;
8+
9+
for (const id of [feedbackContainerId, toolbarContainerId]) {
10+
const host = document.getElementById(id);
11+
if (host?.shadowRoot) {
12+
render(null, host.shadowRoot);
13+
}
14+
host?.remove();
15+
}
16+
}

‎packages/browser-sdk/test/usage.test.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,9 +37,6 @@ const clientNotInitializedError = {
3737
};
3838

3939
vi.mock("../src/sse");
40-
// These tests cover SDK usage, not toolbar rendering. Avoid scheduling Preact
41-
// renders that can outlive the test's browser environment.
42-
vi.mock("../src/toolbar", () => ({ showToolbarToggle: vi.fn() }));
4340
vi.mock("../src/feedback/promptStorage", () => {
4441
return {
4542
markPromptMessageCompleted: vi.fn(),

‎packages/browser-sdk/vitest.setup.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { afterAll, afterEach, beforeAll } from "vitest";
22

3+
import { cleanupUi } from "./test/cleanupUi";
34
import { server } from "./test/mocks/server.js";
45

56
beforeAll(() => {
@@ -11,6 +12,7 @@ beforeAll(() => {
1112
});
1213

1314
afterEach(() => {
15+
cleanupUi();
1416
server.resetHandlers();
1517
});
1618

0 commit comments

Comments
 (0)