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

devAutoConnect.test.ts

266 lines9.7 KB

1import * as NodeModule from "node:module";
2import type { NavigationState, PartialState } from "@react-navigation/native";
3import { expect, it, vi } from "vite-plus/test";
4​
5const requireFromNative = NodeModule.createRequire(
6 NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),
7);
8const requireFromCore = NodeModule.createRequire(
9 requireFromNative.resolve("@react-navigation/core/package.json"),
10);
11const { getActionFromState, getStateFromPath } = requireFromNative("@react-navigation/core") as {
12 readonly getActionFromState: typeof import("@react-navigation/native").getActionFromState;
13 readonly getStateFromPath: typeof import("@react-navigation/native").getStateFromPath;
14};
15const { StackRouter } = requireFromCore("@react-navigation/routers") as {
16 readonly StackRouter: typeof import("@react-navigation/native").StackRouter;
17};
18​
19const harness = vi.hoisted(() => ({
20 pair: vi.fn(),
21 goBack: vi.fn(),
22 dispatch: vi.fn(),
23 columns: false,
24 // The root stack the form sits on when pairing succeeds.
25 rootState: {
26 key: "root",
27 index: 2,
28 routes: [
29 { key: "home", name: "Home" },
30 { key: "settings", name: "Settings" },
31 { key: "new", name: "SettingsEnvironmentNew" },
32 ],
33 },
34 // Navigation that is not ready yet holds callbacks here until the test flushes them.
35 deferred: null as Array<() => void> | null,
36}));
37​
38vi.mock("@react-navigation/native", () => ({
39 StackActions: { replace: vi.fn() },
40 CommonActions: {
41 replaceParams: (params: object) => ({ type: "REPLACE_PARAMS", payload: { params } }),
42 },
43}));
44vi.mock("../../state/use-remote-environment-registry", () => ({
45 pairEnvironment: harness.pair,
46}));
47vi.mock("../layout/workspace/workspace-selection-store", () => ({
48 workspaceHasColumns: () => harness.columns,
49}));
50vi.mock("../../lib/rootNavigation", () => ({
51 rootNavigationRef: {
52 getCurrentRoute: () => harness.rootState.routes[harness.rootState.index],
53 getRootState: () => harness.rootState,
54 getState: () => harness.rootState,
55 getParent: () => undefined,
56 canGoBack: () => true,
57 goBack: harness.goBack,
58 dispatch: harness.dispatch,
59 },
60 whenRootNavigationReady: (navigate: () => void) => {
61 if (harness.deferred) harness.deferred.push(navigate);
62 else navigate();
63 },
64}));
65​
66import { appAtomRegistry } from "../../state/atom-registry";
67import {
68 autoConnectReport,
69 devAutoConnectAttemptAtom,
70 pairingFormLinkAction,
71 startDevAutoConnect,
72} from "./devAutoConnect";
73​
74const PAIRING_URL = "http://192.168.1.10:3773/pair#token=abc";
75​
76function settingsLink(params: object): PartialState<NavigationState> {
77 return {
78 routes: [
79 { name: "Home" },
80 { name: "Settings", state: { routes: [{ name: "SettingsEnvironmentNew", params }] } },
81 ],
82 };
84​
85it("pairs from a nested settings link once, reports failure, and closes the form on success", async () => {
86 vi.stubGlobal("__DEV__", true);
87 const failed = Promise.withResolvers<{ ok: boolean; error: string | null }>();
88 harness.pair.mockReturnValueOnce(failed.promise);
89​
90 const state = settingsLink({ pairingUrl: ` ${PAIRING_URL} `, autoConnect: "1" });
91 expect(startDevAutoConnect(state)).toBe(state);
92 expect(harness.pair).toHaveBeenCalledExactlyOnceWith(PAIRING_URL);
93 expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toEqual({
94 pairingUrl: PAIRING_URL,
95 status: "connecting",
96 });
97​
98 failed.resolve({ ok: false, error: "Pairing code expired." });
99 await failed.promise;
100 await Promise.resolve();
101 expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toEqual({
102 pairingUrl: PAIRING_URL,
103 status: "failed",
104 error: "Pairing code expired.",
105 });
106 expect(harness.goBack).not.toHaveBeenCalled();
107​
108 const succeeded = Promise.withResolvers<{ ok: boolean; error: string | null }>();
109 harness.pair.mockReturnValueOnce(succeeded.promise);
110 startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "true" }));
111 succeeded.resolve({ ok: true, error: null });
112 await succeeded.promise;
113 await Promise.resolve();
114 expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
115 expect(harness.goBack).toHaveBeenCalledOnce();
116});
117​
118it("only prefills without the flag, and ignores the flag in production builds", () => {
119 harness.pair.mockClear();
120 vi.stubGlobal("__DEV__", true);
121 startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
122 vi.stubGlobal("__DEV__", false);
123 startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
124 expect(harness.pair).not.toHaveBeenCalled();
125});
126​
127it("auto-connects in a production bundle only when mobile:metrics built it with the probe", () => {
128 harness.pair.mockClear();
129 harness.pair.mockResolvedValueOnce({ ok: false, error: null });
130 vi.stubGlobal("__DEV__", false);
131 vi.stubEnv("EXPO_PUBLIC_T3_BEHAVIOR_PROBE", "1");
132 startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
133 vi.unstubAllEnvs();
134 expect(harness.pair).toHaveBeenCalledOnce();
135});
136​
137it("forgets a failed auto-connect once the form is opened again without the flag", async () => {
138 vi.stubGlobal("__DEV__", true);
139 const failed = Promise.withResolvers<{ ok: boolean; error: string | null }>();
140 harness.pair.mockReturnValueOnce(failed.promise);
141 startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
142 failed.resolve({ ok: false, error: "Pairing code expired." });
143 await failed.promise;
144 await Promise.resolve();
145 expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toMatchObject({ status: "failed" });
146​
147 startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
148 expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
149});
150​
151it("drops the result of a pairing that a later link superseded", async () => {
152 vi.stubGlobal("__DEV__", true);
153 const stale = Promise.withResolvers<{ ok: boolean; error: string | null }>();
154 harness.pair.mockReturnValueOnce(stale.promise);
155 startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
156 startDevAutoConnect(settingsLink({ pairingUrl: PAIRING_URL }));
157​
158 stale.resolve({ ok: false, error: "Pairing code expired." });
159 await stale.promise;
160 await Promise.resolve();
161 expect(appAtomRegistry.get(devAutoConnectAttemptAtom)).toBeNull();
162});
163​
164it("keeps Connect busy while the auto-connect runs, even after the user edits the form", () => {
165 const connecting = { pairingUrl: PAIRING_URL, status: "connecting" } as const;
166 expect(autoConnectReport(connecting, PAIRING_URL, true)).toEqual({
167 connecting: true,
168 error: null,
169 });
170 const failed = { pairingUrl: PAIRING_URL, status: "failed", error: "Expired." } as const;
171 expect(autoConnectReport(failed, PAIRING_URL, false)).toEqual({
172 connecting: false,
173 error: "Expired.",
174 });
175 expect(autoConnectReport(failed, PAIRING_URL, true).error).toBeNull();
176 expect(autoConnectReport(connecting, "http://other/pair#token=x", false).connecting).toBe(false);
177});
178​
179async function pairSuccessfully(link: PartialState<NavigationState>) {
180 const succeeded = Promise.withResolvers<{ ok: boolean; error: string | null }>();
181 harness.pair.mockReturnValueOnce(succeeded.promise);
182 startDevAutoConnect(link);
183 succeeded.resolve({ ok: true, error: null });
184 await succeeded.promise;
185 await Promise.resolve();
187​
188it("on columns, a successful settings link shows Environments instead of an empty detail", async () => {
189 vi.stubGlobal("__DEV__", true);
190 harness.goBack.mockClear();
191 harness.dispatch.mockClear();
192 harness.columns = true;
193 await pairSuccessfully(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
194 harness.columns = false;
195​
196 expect(harness.goBack).not.toHaveBeenCalled();
197 expect(harness.dispatch).toHaveBeenCalledExactlyOnceWith({
198 type: "RESET",
199 target: "root",
200 payload: expect.objectContaining({
201 index: 2,
202 routes: [
203 { key: "home", name: "Home" },
204 { key: "settings", name: "Settings" },
205 { name: "SettingsEnvironments", params: undefined },
206 ],
207 }),
208 });
209});
210​
211it("a success that waited for navigation leaves a newer link's form open", async () => {
212 vi.stubGlobal("__DEV__", true);
213 harness.goBack.mockClear();
214 harness.dispatch.mockClear();
215 harness.deferred = [];
216 await pairSuccessfully(settingsLink({ pairingUrl: PAIRING_URL, autoConnect: "1" }));
217 startDevAutoConnect(settingsLink({ pairingUrl: "http://192.168.1.11:3773/pair#token=def" }));
218​
219 const deferred = harness.deferred;
220 harness.deferred = null;
221 for (const navigate of deferred) navigate();
222 expect(harness.goBack).not.toHaveBeenCalled();
223 expect(harness.dispatch).not.toHaveBeenCalled();
224});
225​
226it("a pairing link fills the pairing form already on screen instead of stacking a second one", () => {
227 const linking = {
228 initialRouteName: "Home",
229 screens: {
230 Home: "",
231 Settings: "settings",
232 SettingsEnvironmentNew: "settings/environment-new",
233 ConnectionsNew: "connections/new",
234 },
235 };
236 const router = StackRouter({});
237 const options = {
238 routeNames: Object.keys(linking.screens),
239 routeParamList: {},
240 routeGetIdList: {},
241 };
242 // Settings > Environments > Add environment, as the user opened it.
243 const open = router.getRehydratedState(
244 {
245 index: 2,
246 routes: [{ name: "Home" }, { name: "Settings" }, { name: "SettingsEnvironmentNew" }],
247 },
248 options,
249 );
250 const link = getStateFromPath(
251 `connections/new?pairingUrl=${encodeURIComponent(PAIRING_URL)}`,
252 linking,
253 )!;
254 const action = pairingFormLinkAction(link, open) ?? getActionFromState(link, linking)!;
255 const next = router.getStateForAction(open, { target: open.key, ...action }, options);
256​
257 expect(next?.routes.map((route) => route.name)).toEqual([
258 "Home",
259 "Settings",
260 "SettingsEnvironmentNew",
261 ]);
262 expect(next?.routes.at(-1)).toMatchObject({
263 key: open.routes[2]!.key,
264 params: { pairingUrl: PAIRING_URL },
265 });
266});