Open History to see the last commit
1import { describe, expect, it, vi } from "vite-plus/test";
2
3import {
4 createAppUpdateDeferral,
5 createAppUpdateLaunchCheck,
6 runAppUpdateCheck,
7 type AppUpdateCheckState,
8 type AppUpdateClient,
9 type AppUpdateEnvironment,
10} from "./app-updates";
11
12vi.mock("expo-updates", () => ({
13 isEnabled: true,
14 checkForUpdateAsync: vi.fn(),
15 fetchUpdateAsync: vi.fn(),
16 reloadAsync: vi.fn(),
17}));
18
19vi.mock("react-native", () => ({
20 AppState: {
21 currentState: "active",
22 addEventListener: vi.fn(() => ({ remove: vi.fn() })),
23 },
24}));
25
26function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateClient {
27 return {
28 isEnabled: true,
29 checkForUpdateAsync: vi.fn(async () => ({
30 isAvailable: false,
31 isRollBackToEmbedded: false,
32 })),
33 fetchUpdateAsync: vi.fn(async () => ({
34 isNew: true,
35 isRollBackToEmbedded: false,
36 })),
37 reloadAsync: vi.fn(async () => {}),
38 ...overrides,
39 };
40}
41
42function makeUpdateEnvironment(overrides: Partial<AppUpdateEnvironment> = {}): {
43 readonly backgroundCallbacks: Array<() => void>;
44 readonly environment: AppUpdateEnvironment;
45 readonly foregroundStayCallbacks: Array<() => void>;
46} {
47 const backgroundCallbacks: Array<() => void> = [];
48 const foregroundStayCallbacks: Array<() => void> = [];
49 return {
50 backgroundCallbacks,
51 foregroundStayCallbacks,
52 environment: {
53 confirmInstallNow: vi.fn(async () => true),
54 flushPendingWrites: vi.fn(async () => {}),
55 isSafeToRestartInBackground: vi.fn(async () => true),
56 onNextBackground: vi.fn((apply: () => void, _includeCurrent: boolean) => {
57 backgroundCallbacks.push(apply);
58 }),
59 onForegroundStay: vi.fn((apply: () => void) => {
60 foregroundStayCallbacks.push(apply);
61 }),
62 ...overrides,
63 },
64 };
65}
66
67function makeAvailableUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateClient {
68 return makeUpdateClient({
69 checkForUpdateAsync: vi.fn(async () => ({
70 isAvailable: true,
71 isRollBackToEmbedded: false,
72 })),
73 ...overrides,
74 });
75}
76
77describe("runAppUpdateCheck", () => {
78 it("flushes pending writes before restarting", async () => {
79 const client = makeAvailableUpdateClient();
80 const { environment } = makeUpdateEnvironment();
81
82 await runAppUpdateCheck({
83 applyMode: "immediate",
84 client,
85 deferral: createAppUpdateDeferral(),
86 environment,
87 });
88
89 const flushOrder = vi.mocked(environment.flushPendingWrites).mock.invocationCallOrder[0]!;
90 const reloadOrder = vi.mocked(client.reloadAsync).mock.invocationCallOrder[0]!;
91 expect(flushOrder).toBeLessThan(reloadOrder);
92 });
93
94 it("restarts into an already-downloaded update when the user asks to install", async () => {
95 const client = makeUpdateClient();
96 const { environment } = makeUpdateEnvironment();
97 const deferral = createAppUpdateDeferral();
98 deferral.pendingInstall = true;
99
100 await runAppUpdateCheck({ applyMode: "immediate", client, deferral, environment });
101
102 expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
103 expect(client.reloadAsync).toHaveBeenCalledOnce();
104 });
105
106 it("honors an immediate request that joined an in-flight background check", async () => {
107 let resolveCheck!: (result: {
108 readonly isAvailable: boolean;
109 readonly isRollBackToEmbedded: boolean;
110 }) => void;
111 const checkResult = new Promise<{
112 readonly isAvailable: boolean;
113 readonly isRollBackToEmbedded: boolean;
114 }>((resolve) => {
115 resolveCheck = resolve;
116 });
117 const client = makeUpdateClient({
118 checkForUpdateAsync: vi.fn(() => checkResult),
119 });
120 const { environment } = makeUpdateEnvironment();
121 const deferral = createAppUpdateDeferral();
122
123 const backgroundCheck = runAppUpdateCheck({ client, deferral, environment });
124 const manualCheck = runAppUpdateCheck({
125 applyMode: "immediate",
126 client,
127 deferral,
128 environment,
129 });
130
131 resolveCheck({ isAvailable: true, isRollBackToEmbedded: false });
132 await Promise.all([backgroundCheck, manualCheck]);
133
134 expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
135 expect(client.reloadAsync).toHaveBeenCalledOnce();
136 });
137
138 it("holds the deferred restart and re-arms when the pre-restart flush fails", async () => {
139 const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
140 const client = makeAvailableUpdateClient();
141 const { backgroundCallbacks, environment } = makeUpdateEnvironment({
142 flushPendingWrites: vi.fn(async () => {
143 throw new Error("disk full");
144 }),
145 });
146 const deferral = createAppUpdateDeferral();
147
148 await runAppUpdateCheck({ client, deferral, environment });
149 backgroundCallbacks[0]!();
150
151 await vi.waitFor(() => expect(backgroundCallbacks).toHaveLength(2));
152 expect(client.reloadAsync).not.toHaveBeenCalled();
153 expect(deferral.pendingInstall).toBe(true);
154 reportError.mockRestore();
155 });
156
157 it("still restarts a user-requested install when the flush fails", async () => {
158 const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
159 const client = makeAvailableUpdateClient();
160 const { environment } = makeUpdateEnvironment({
161 flushPendingWrites: vi.fn(async () => {
162 throw new Error("storage unavailable");
163 }),
164 });
165
166 await runAppUpdateCheck({
167 applyMode: "immediate",
168 client,
169 deferral: createAppUpdateDeferral(),
170 environment,
171 });
172
173 expect(client.reloadAsync).toHaveBeenCalledOnce();
174 reportError.mockRestore();
175 });
176
177 it("restarts into the embedded bundle for a rollback directive", async () => {
178 const client = makeUpdateClient({
179 checkForUpdateAsync: vi.fn(async () => ({
180 isAvailable: false,
181 isRollBackToEmbedded: true,
182 })),
183 fetchUpdateAsync: vi.fn(async () => ({
184 isNew: false,
185 isRollBackToEmbedded: true,
186 })),
187 });
188 const { environment } = makeUpdateEnvironment();
189
190 await runAppUpdateCheck({ client, deferral: createAppUpdateDeferral(), environment });
191
192 expect(client.fetchUpdateAsync).toHaveBeenCalledOnce();
193 expect(environment.confirmInstallNow).not.toHaveBeenCalled();
194 expect(client.reloadAsync).toHaveBeenCalledOnce();
195 });
196
197 it.each(["ERR_NOT_AVAILABLE_IN_DEV_CLIENT", "ERR_UPDATES_DISABLED"])(
198 "treats Expo's %s failure as an unavailable update check",
199 async (code) => {
200 const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
201 const error = Object.assign(new Error("Updates are unavailable"), { code });
202 const client = makeUpdateClient({
203 checkForUpdateAsync: vi.fn(async () => {
204 throw error;
205 }),
206 });
207 const failures: string[] = [];
208 const states: AppUpdateCheckState[] = [];
209
210 await runAppUpdateCheck({
211 client,
212 onFailure: (message) => failures.push(message),
213 onStateChange: (state) => states.push(state),
214 });
215
216 expect(reportError).not.toHaveBeenCalled();
217 expect(failures).toEqual([]);
218 expect(states).toEqual(["checking", "idle"]);
219 reportError.mockRestore();
220 },
221 );
222
223 it("coalesces overlapping launch and manual checks", async () => {
224 let resolveCheck!: (result: {
225 readonly isAvailable: boolean;
226 readonly isRollBackToEmbedded: boolean;
227 }) => void;
228 const checkResult = new Promise<{
229 readonly isAvailable: boolean;
230 readonly isRollBackToEmbedded: boolean;
231 }>((resolve) => {
232 resolveCheck = resolve;
233 });
234 const client = makeUpdateClient({
235 checkForUpdateAsync: vi.fn(() => checkResult),
236 });
237 const checkOnLaunch = createAppUpdateLaunchCheck(client);
238 const manualStates: AppUpdateCheckState[] = [];
239
240 const launchCheck = checkOnLaunch();
241 const manualCheck = runAppUpdateCheck({
242 client,
243 onStateChange: (state) => manualStates.push(state),
244 });
245
246 expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
247 expect(manualStates).toEqual(["checking"]);
248
249 resolveCheck({
250 isAvailable: false,
251 isRollBackToEmbedded: false,
252 });
253 await Promise.all([launchCheck, manualCheck]);
254
255 expect(manualStates).toEqual(["checking", "current"]);
256
257 await runAppUpdateCheck({ client });
258 expect(client.checkForUpdateAsync).toHaveBeenCalledTimes(2);
259 });
260
261 it("publishes the in-flight check before a state callback can re-enter", async () => {
262 let resolveCheck!: (result: {
263 readonly isAvailable: boolean;
264 readonly isRollBackToEmbedded: boolean;
265 }) => void;
266 const checkResult = new Promise<{
267 readonly isAvailable: boolean;
268 readonly isRollBackToEmbedded: boolean;
269 }>((resolve) => {
270 resolveCheck = resolve;
271 });
272 const client = makeUpdateClient({
273 checkForUpdateAsync: vi.fn(() => checkResult),
274 });
275 const reentrantStates: AppUpdateCheckState[] = [];
276 let reentrantCheck: Promise<void> | undefined;
277 let didReenter = false;
278
279 const initialCheck = runAppUpdateCheck({
280 client,
281 onStateChange: (state) => {
282 if (state !== "checking" || didReenter) return;
283 didReenter = true;
284 reentrantCheck = runAppUpdateCheck({
285 client,
286 onStateChange: (reentrantState) => reentrantStates.push(reentrantState),
287 });
288 },
289 });
290
291 expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
292 expect(reentrantCheck).toBeDefined();
293 expect(reentrantStates).toEqual(["checking"]);
294
295 resolveCheck({
296 isAvailable: false,
297 isRollBackToEmbedded: false,
298 });
299 await Promise.all([initialCheck, reentrantCheck]);
300
301 expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
302 expect(reentrantStates).toEqual(["checking", "current"]);
303 });
304});
305
306describe("createAppUpdateLaunchCheck", () => {
307 it("checks at most once for each JavaScript launch", async () => {
308 const client = makeUpdateClient();
309 const checkOnLaunch = createAppUpdateLaunchCheck(client);
310
311 const first = checkOnLaunch();
312 const second = checkOnLaunch();
313 await first;
314
315 expect(second).toBeUndefined();
316 expect(client.checkForUpdateAsync).toHaveBeenCalledOnce();
317 });
318});