| 1 | import { afterEach, describe, expect, it, vi } from "vite-plus/test"; |
| 2 | import { subscribeDeviceForeground } from "./deviceHubApi"; |
| 3 | |
| 4 | describe("foreground app events", () => { |
| 5 | afterEach(() => vi.unstubAllGlobals()); |
| 6 | |
| 7 | it("clears the last app when it exits and ignores malformed events", () => { |
| 8 | let source: FakeEventSource; |
| 9 | class FakeEventSource { |
| 10 | onmessage: ((event: { data: string }) => void) | null = null; |
| 11 | addEventListener(_type: string, listener: (event: { data: string }) => void) { |
| 12 | this.onmessage = listener; |
| 13 | } |
| 14 | close = vi.fn(); |
| 15 | constructor() { |
| 16 | source = this; |
| 17 | } |
| 18 | } |
| 19 | vi.stubGlobal("EventSource", FakeEventSource); |
| 20 | const onChange = vi.fn(); |
| 21 | const stop = subscribeDeviceForeground( |
| 22 | { |
| 23 | platform: "ios", |
| 24 | deviceId: "test", |
| 25 | access: { httpBase: "http://test", wsBase: "ws://test", query: {}, credentials: true }, |
| 26 | }, |
| 27 | onChange, |
| 28 | ); |
| 29 | const emit = (data: unknown) => source.onmessage?.({ data: JSON.stringify(data) }); |
| 30 | emit({ bundleId: "com.example.app", pid: 123 }); |
| 31 | emit({ bundleId: null }); |
| 32 | emit({ bundleId: "com.example.other" }); |
| 33 | emit({ bundleId: "" }); |
| 34 | emit({ other: "not app state" }); |
| 35 | expect(onChange.mock.calls.map(([app]) => app)).toEqual([ |
| 36 | { id: "com.example.app", pid: 123 }, |
| 37 | null, |
| 38 | { id: "com.example.other" }, |
| 39 | null, |
| 40 | ]); |
| 41 | stop(); |
| 42 | expect(source!.close).toHaveBeenCalledOnce(); |
| 43 | }); |
| 44 | }); |