| 1 | import { afterEach, describe, expect, it } from "vite-plus/test"; |
| 2 | |
| 3 | import { subscribeToTerminalFocusChanges } from "./useTerminalFocus"; |
| 4 | |
| 5 | const originalWindow = globalThis.window; |
| 6 | |
| 7 | afterEach(() => { |
| 8 | if (originalWindow === undefined) { |
| 9 | delete (globalThis as { window?: Window }).window; |
| 10 | } else { |
| 11 | globalThis.window = originalWindow; |
| 12 | } |
| 13 | }); |
| 14 | |
| 15 | describe("subscribeToTerminalFocusChanges", () => { |
| 16 | it("notifies on focus transitions until unsubscribed", () => { |
| 17 | const listeners = new Map<string, Set<() => void>>(); |
| 18 | globalThis.window = { |
| 19 | addEventListener: (type: string, listener: EventListenerOrEventListenerObject) => { |
| 20 | const callbacks = listeners.get(type) ?? new Set<() => void>(); |
| 21 | callbacks.add(listener as () => void); |
| 22 | listeners.set(type, callbacks); |
| 23 | }, |
| 24 | removeEventListener: (type: string, listener: EventListenerOrEventListenerObject) => { |
| 25 | listeners.get(type)?.delete(listener as () => void); |
| 26 | }, |
| 27 | } as unknown as Window & typeof globalThis; |
| 28 | let notifications = 0; |
| 29 | |
| 30 | const unsubscribe = subscribeToTerminalFocusChanges(() => { |
| 31 | notifications += 1; |
| 32 | }); |
| 33 | |
| 34 | for (const listener of listeners.get("focusin") ?? []) listener(); |
| 35 | for (const listener of listeners.get("focusout") ?? []) listener(); |
| 36 | expect(notifications).toBe(2); |
| 37 | |
| 38 | unsubscribe(); |
| 39 | for (const listener of listeners.get("focusin") ?? []) listener(); |
| 40 | expect(notifications).toBe(2); |
| 41 | }); |
| 42 | }); |