Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

wsConnectionState.test.ts

75 lines2.4 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2​
3import {
4 getWsConnectionStatus,
5 getWsReconnectDelayMsForRetry,
6 getWsConnectionUiState,
7 recordWsConnectionAttempt,
8 recordWsConnectionClosed,
9 recordWsConnectionErrored,
10 recordWsConnectionOpened,
11 resetWsConnectionStateForTests,
12 setBrowserOnlineStatus,
13 WS_RECONNECT_MAX_ATTEMPTS,
14} from "./wsConnectionState";
15​
16describe("wsConnectionState", () => {
17 beforeEach(() => {
18 vi.useFakeTimers();
19 vi.setSystemTime(new Date("2026-04-03T20:30:00.000Z"));
20 resetWsConnectionStateForTests();
21 });
22​
23 afterEach(() => {
24 vi.useRealTimers();
25 });
26​
27 it("treats a disconnected browser as offline once the websocket drops", () => {
28 recordWsConnectionAttempt("ws://localhost:3020/ws");
29 recordWsConnectionOpened();
30 recordWsConnectionClosed({ code: 1006, reason: "offline" });
31 setBrowserOnlineStatus(false);
32​
33 expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("offline");
34 });
35​
36 it("stays in the initial connecting state until the first disconnect", () => {
37 recordWsConnectionAttempt("ws://localhost:3020/ws");
38​
39 expect(getWsConnectionStatus()).toMatchObject({
40 attemptCount: 1,
41 hasConnected: false,
42 phase: "connecting",
43 });
44 expect(getWsConnectionUiState(getWsConnectionStatus())).toBe("connecting");
45 });
46​
47 it("schedules the next retry after a failed websocket attempt", () => {
48 recordWsConnectionAttempt("ws://localhost:3020/ws");
49 recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
50​
51 const firstRetryDelayMs = getWsReconnectDelayMsForRetry(0);
52 if (firstRetryDelayMs === null) {
53 throw new Error("Expected an initial retry delay.");
54 }
55​
56 expect(getWsConnectionStatus()).toMatchObject({
57 nextRetryAt: new Date(Date.now() + firstRetryDelayMs).toISOString(),
58 reconnectAttemptCount: 1,
59 reconnectPhase: "waiting",
60 });
61 });
62​
63 it("marks the reconnect cycle as exhausted after the final attempt fails", () => {
64 for (let attempt = 0; attempt < WS_RECONNECT_MAX_ATTEMPTS; attempt += 1) {
65 recordWsConnectionAttempt("ws://localhost:3020/ws");
66 recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
67 }
68​
69 expect(getWsConnectionStatus()).toMatchObject({
70 nextRetryAt: null,
71 reconnectAttemptCount: WS_RECONNECT_MAX_ATTEMPTS,
72 reconnectPhase: "exhausted",
73 });
74 });
75});