@terreno/test 57.18.0 → 57.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +1681 -0
  2. package/README.md +6 -0
  3. package/dist/assertions/expectAPIError.d.ts +18 -0
  4. package/dist/assertions/expectAPIError.js +33 -0
  5. package/dist/assertions/strictResponseProperties.d.ts +14 -0
  6. package/dist/assertions/strictResponseProperties.js +37 -0
  7. package/dist/cache/mongoTestCache.js +2 -2
  8. package/dist/cli/collectFiles.d.ts +38 -0
  9. package/dist/cli/collectFiles.js +73 -0
  10. package/dist/cli/testHygiene.d.ts +134 -0
  11. package/dist/cli/testHygiene.js +357 -0
  12. package/dist/cli/testHygieneCli.d.ts +2 -0
  13. package/dist/cli/testHygieneCli.js +5 -0
  14. package/dist/cli/testHygieneRules.d.ts +58 -0
  15. package/dist/cli/testHygieneRules.js +517 -0
  16. package/dist/cli/testShard.d.ts +155 -0
  17. package/dist/cli/testShard.js +377 -0
  18. package/dist/cli/testShardCli.d.ts +2 -0
  19. package/dist/cli/testShardCli.js +5 -0
  20. package/dist/expo/authTokenStorage.d.ts +76 -0
  21. package/dist/expo/authTokenStorage.js +160 -0
  22. package/dist/expo/expoModuleMocks.d.ts +24 -0
  23. package/dist/expo/expoModuleMocks.js +456 -0
  24. package/dist/expo/libraryModuleMocks.d.ts +17 -0
  25. package/dist/expo/libraryModuleMocks.js +347 -0
  26. package/dist/expo/mockHelpers.d.ts +39 -0
  27. package/dist/expo/mockHelpers.js +45 -0
  28. package/dist/expo/mockModuleAliases.d.ts +50 -0
  29. package/dist/expo/mockModuleAliases.js +174 -0
  30. package/dist/expo/reactNativeMock.d.ts +39 -0
  31. package/dist/expo/reactNativeMock.js +421 -0
  32. package/dist/expo/registerExpoTestEnvironment.d.ts +69 -0
  33. package/dist/expo/registerExpoTestEnvironment.js +163 -0
  34. package/dist/expo/renderWithTerreno.d.ts +47 -0
  35. package/dist/expo/renderWithTerreno.js +47 -0
  36. package/dist/http/authWithToken.d.ts +20 -0
  37. package/dist/http/authWithToken.js +30 -0
  38. package/dist/index.d.ts +14 -1
  39. package/dist/index.js +33 -1
  40. package/dist/logging/silenceLogs.js +0 -2
  41. package/dist/mocks/aiSdk.d.ts +77 -0
  42. package/dist/mocks/aiSdk.js +102 -0
  43. package/dist/mocks/cloudTasks.d.ts +91 -0
  44. package/dist/mocks/cloudTasks.js +197 -0
  45. package/dist/mocks/expoPush.d.ts +53 -0
  46. package/dist/mocks/expoPush.js +57 -0
  47. package/dist/mocks/gcs.d.ts +101 -0
  48. package/dist/mocks/gcs.js +162 -0
  49. package/dist/mocks/googleAuth.d.ts +69 -0
  50. package/dist/mocks/googleAuth.js +55 -0
  51. package/dist/mocks/mockGroup.d.ts +11 -0
  52. package/dist/mocks/mockGroup.js +21 -0
  53. package/dist/mocks/notifiers.d.ts +21 -0
  54. package/dist/mocks/notifiers.js +26 -0
  55. package/dist/mocks/sendgrid.d.ts +22 -0
  56. package/dist/mocks/sendgrid.js +32 -0
  57. package/dist/mocks/twilio.d.ts +72 -0
  58. package/dist/mocks/twilio.js +64 -0
  59. package/dist/preload/registerBackendPreload.js +4 -1
  60. package/dist/time/freezeTime.d.ts +16 -0
  61. package/dist/time/freezeTime.js +49 -0
  62. package/dist/transaction/testTransaction.d.ts +43 -6
  63. package/dist/transaction/testTransaction.js +371 -92
  64. package/dist/utils/waitUntil.d.ts +22 -0
  65. package/dist/utils/waitUntil.js +34 -0
  66. package/package.json +53 -8
  67. package/src/assertions/expectAPIError.ts +51 -0
  68. package/src/assertions/strictResponseProperties.ts +42 -0
  69. package/src/cache/mongoTestCache.ts +2 -2
  70. package/src/cli/collectFiles.ts +115 -0
  71. package/src/cli/testHygiene.ts +539 -0
  72. package/src/cli/testHygieneCli.ts +4 -0
  73. package/src/cli/testHygieneRules.ts +719 -0
  74. package/src/cli/testShard.ts +532 -0
  75. package/src/cli/testShardCli.ts +4 -0
  76. package/src/expo/authTokenStorage.ts +198 -0
  77. package/src/expo/expoModuleMocks.ts +503 -0
  78. package/src/expo/libraryModuleMocks.ts +411 -0
  79. package/src/expo/mockHelpers.ts +73 -0
  80. package/src/expo/mockModuleAliases.ts +252 -0
  81. package/src/expo/reactNativeMock.ts +534 -0
  82. package/src/expo/registerExpoTestEnvironment.ts +260 -0
  83. package/src/expo/renderWithTerreno.ts +79 -0
  84. package/src/http/authWithToken.ts +38 -0
  85. package/src/index.ts +82 -1
  86. package/src/logging/silenceLogs.ts +0 -2
  87. package/src/mocks/aiSdk.ts +199 -0
  88. package/src/mocks/cloudTasks.ts +323 -0
  89. package/src/mocks/expoPush.ts +134 -0
  90. package/src/mocks/gcs.ts +305 -0
  91. package/src/mocks/googleAuth.ts +136 -0
  92. package/src/mocks/mockGroup.ts +32 -0
  93. package/src/mocks/notifiers.ts +36 -0
  94. package/src/mocks/sendgrid.ts +57 -0
  95. package/src/mocks/twilio.ts +143 -0
  96. package/src/preload/registerBackendPreload.ts +4 -1
  97. package/src/time/freezeTime.ts +61 -0
  98. package/src/transaction/testTransaction.ts +456 -124
  99. package/src/utils/waitUntil.ts +47 -0
  100. package/biome.jsonc +0 -20
  101. package/bunfig.toml +0 -16
  102. package/src/cache/mongoTestCache.test.ts +0 -103
  103. package/src/env/setTerrenoTestEnv.test.ts +0 -26
  104. package/src/http/authAsUser.test.ts +0 -40
  105. package/src/http/getBaseServer.test.ts +0 -45
  106. package/src/logging/setupEnvironment.test.ts +0 -24
  107. package/src/logging/silenceLogs.test.ts +0 -52
  108. package/src/logging/testLogger.test.ts +0 -58
  109. package/src/mocks/sentryBun.test.ts +0 -230
  110. package/src/mongo/connection.test.ts +0 -43
  111. package/src/mongo/mongoServer.test.ts +0 -99
  112. package/src/preload/registerBackendPreload.test.ts +0 -10
  113. package/src/transaction/testTransaction.test.ts +0 -64
  114. package/src/utils/helpers.test.ts +0 -46
  115. package/tsconfig.json +0 -18
@@ -0,0 +1,198 @@
1
+ import {type Mock, mock} from "bun:test";
2
+
3
+ import type {ModuleExports, ModuleMockMap} from "./mockHelpers";
4
+
5
+ /** Keys `@terreno/rtk` JWT auth (`generateAuthSlice`, `emptyApi`) reads and writes. */
6
+ export const TERRENO_AUTH_TOKEN_KEYS = {
7
+ authToken: "AUTH_TOKEN",
8
+ refreshToken: "REFRESH_TOKEN",
9
+ } as const;
10
+
11
+ /** Default `storagePrefix` `@terreno/rtk`'s `createBetterAuthClient` uses. */
12
+ const DEFAULT_BETTER_AUTH_STORAGE_PREFIX = "terreno";
13
+
14
+ /**
15
+ * Keys a `@terreno/rtk` Better Auth client stores under: the `@better-auth/expo` cookie jar and
16
+ * session cache (native), and the bearer token (web, `webAuth: "bearer"`).
17
+ */
18
+ export const getBetterAuthStorageKeys = (
19
+ storagePrefix: string = DEFAULT_BETTER_AUTH_STORAGE_PREFIX
20
+ ): {bearerToken: string; cookie: string; sessionData: string} => ({
21
+ bearerToken: `${storagePrefix}_bearer_token`,
22
+ cookie: `${storagePrefix}_cookie`,
23
+ sessionData: `${storagePrefix}_session_data`,
24
+ });
25
+
26
+ /** In-memory backing store for the `expo-secure-store` stand-in. Tests may read it directly. */
27
+ export const secureStore: Record<string, string> = {};
28
+
29
+ /** In-memory backing store for the AsyncStorage stand-in. Tests may read it directly. */
30
+ export const asyncStorage: Record<string, string> = {};
31
+
32
+ const readKey = (store: Record<string, string>, key: string): string | null =>
33
+ Object.hasOwn(store, key) ? (store[key] as string) : null;
34
+
35
+ const writeKey = (store: Record<string, string>, key: string, value: string): void => {
36
+ store[key] = String(value);
37
+ };
38
+
39
+ const deleteKey = (store: Record<string, string>, key: string): void => {
40
+ delete store[key];
41
+ };
42
+
43
+ const emptyStore = (store: Record<string, string>): void => {
44
+ for (const key of Object.keys(store)) {
45
+ delete store[key];
46
+ }
47
+ };
48
+
49
+ /** The implementation each storage mock is reset to, so a `mockImplementation` cannot leak. */
50
+ const secureStoreImplementations = {
51
+ deleteItemAsync: async (key: string): Promise<void> => deleteKey(secureStore, key),
52
+ getItem: (key: string): string | null => readKey(secureStore, key),
53
+ getItemAsync: async (key: string): Promise<string | null> => readKey(secureStore, key),
54
+ isAvailableAsync: async (): Promise<boolean> => true,
55
+ setItem: (key: string, value: string): void => writeKey(secureStore, key, value),
56
+ setItemAsync: async (key: string, value: string): Promise<void> =>
57
+ writeKey(secureStore, key, value),
58
+ };
59
+
60
+ const asyncStorageImplementations = {
61
+ clear: async (): Promise<void> => emptyStore(asyncStorage),
62
+ getAllKeys: async (): Promise<string[]> => Object.keys(asyncStorage),
63
+ getItem: async (key: string): Promise<string | null> => readKey(asyncStorage, key),
64
+ mergeItem: async (key: string, value: string): Promise<void> => {
65
+ const current = JSON.parse(readKey(asyncStorage, key) ?? "{}") as Record<string, unknown>;
66
+ writeKey(asyncStorage, key, JSON.stringify({...current, ...JSON.parse(value)}));
67
+ },
68
+ multiGet: async (keys: readonly string[]): Promise<[string, string | null][]> =>
69
+ keys.map((key) => [key, readKey(asyncStorage, key)]),
70
+ multiRemove: async (keys: readonly string[]): Promise<void> => {
71
+ for (const key of keys) {
72
+ deleteKey(asyncStorage, key);
73
+ }
74
+ },
75
+ multiSet: async (pairs: readonly [string, string][]): Promise<void> => {
76
+ for (const [key, value] of pairs) {
77
+ writeKey(asyncStorage, key, value);
78
+ }
79
+ },
80
+ removeItem: async (key: string): Promise<void> => deleteKey(asyncStorage, key),
81
+ setItem: async (key: string, value: string): Promise<void> => writeKey(asyncStorage, key, value),
82
+ };
83
+
84
+ type MockedApi<T extends Record<string, (...args: never[]) => unknown>> = {
85
+ [K in keyof T]: Mock<T[K]>;
86
+ };
87
+
88
+ const mockApi = <T extends Record<string, (...args: never[]) => unknown>>(
89
+ implementations: T
90
+ ): MockedApi<T> => {
91
+ const api = {} as MockedApi<T>;
92
+ for (const key of Object.keys(implementations) as (keyof T)[]) {
93
+ api[key] = mock(implementations[key]) as unknown as MockedApi<T>[typeof key];
94
+ }
95
+ return api;
96
+ };
97
+
98
+ /** Stable `expo-secure-store` stand-in backed by `secureStore` (sync and async APIs). */
99
+ export const secureStoreMock = mockApi(secureStoreImplementations);
100
+
101
+ /** Stable `@react-native-async-storage/async-storage` stand-in backed by `asyncStorage`. */
102
+ export const asyncStorageMock = mockApi(asyncStorageImplementations);
103
+
104
+ const resetApi = <T extends Record<string, (...args: never[]) => unknown>>(
105
+ api: MockedApi<T>,
106
+ implementations: T
107
+ ): void => {
108
+ for (const key of Object.keys(implementations) as (keyof T)[]) {
109
+ api[key].mockClear();
110
+ (api[key].mockImplementation as (fn: T[keyof T]) => unknown)(implementations[key]);
111
+ }
112
+ };
113
+
114
+ /** Module factories for the two storage packages, for composing into a larger mock map. */
115
+ export const createAuthTokenStorageModuleMocks = (): ModuleMockMap => ({
116
+ "@react-native-async-storage/async-storage": (): ModuleExports => ({
117
+ ...asyncStorageMock,
118
+ default: asyncStorageMock,
119
+ }),
120
+ "expo-secure-store": (): ModuleExports => ({
121
+ ...secureStoreMock,
122
+ AFTER_FIRST_UNLOCK: 0,
123
+ AFTER_FIRST_UNLOCK_THIS_DEVICE_ONLY: 1,
124
+ ALWAYS: 2,
125
+ ALWAYS_THIS_DEVICE_ONLY: 4,
126
+ WHEN_PASSCODE_SET_THIS_DEVICE_ONLY: 3,
127
+ WHEN_UNLOCKED: 5,
128
+ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 6,
129
+ }),
130
+ });
131
+
132
+ /**
133
+ * Points every storage mock back at its in-memory implementation and clears its call history,
134
+ * undoing a suite's `mockImplementation`, `mockReset()`, or `jest.clearAllMocks()`.
135
+ */
136
+ export const resetAuthTokenStorageMocks = (): void => {
137
+ resetApi(secureStoreMock, secureStoreImplementations);
138
+ resetApi(asyncStorageMock, asyncStorageImplementations);
139
+ };
140
+
141
+ /**
142
+ * Registers in-memory `expo-secure-store` and AsyncStorage mocks and resets them
143
+ * (`resetAuthTokenStorageMocks`). Call it again from `beforeEach` when another suite in the same
144
+ * process registers its own SecureStore or AsyncStorage mock.
145
+ */
146
+ export const registerAuthTokenStorageMocks = (): void => {
147
+ for (const [specifier, factory] of Object.entries(createAuthTokenStorageModuleMocks())) {
148
+ mock.module(specifier, factory);
149
+ }
150
+ resetAuthTokenStorageMocks();
151
+ };
152
+
153
+ /**
154
+ * Removes stored values from both in-memory stores. With `keys`, removes only those keys;
155
+ * without, empties both stores so nothing a test wrote leaks into the next one.
156
+ */
157
+ export const clearAuthTokenStorage = ({keys}: {keys?: readonly string[]} = {}): void => {
158
+ if (!keys) {
159
+ emptyStore(secureStore);
160
+ emptyStore(asyncStorage);
161
+ return;
162
+ }
163
+ for (const key of keys) {
164
+ deleteKey(secureStore, key);
165
+ deleteKey(asyncStorage, key);
166
+ }
167
+ };
168
+
169
+ /** Where `setAuthTokens` writes: native reads SecureStore, web reads AsyncStorage. */
170
+ export type AuthTokenStorageTarget = "asyncStorage" | "both" | "secureStore";
171
+
172
+ /**
173
+ * Seeds the JWT tokens `@terreno/rtk` reads (`AUTH_TOKEN` / `REFRESH_TOKEN`), so a test can
174
+ * start signed in. Writes to SecureStore (native) by default.
175
+ */
176
+ export const setAuthTokens = ({
177
+ authToken,
178
+ refreshToken,
179
+ target = "secureStore",
180
+ }: {
181
+ authToken: string;
182
+ refreshToken?: string;
183
+ target?: AuthTokenStorageTarget;
184
+ }): void => {
185
+ const stores: Record<string, string>[] = [];
186
+ if (target !== "asyncStorage") {
187
+ stores.push(secureStore);
188
+ }
189
+ if (target !== "secureStore") {
190
+ stores.push(asyncStorage);
191
+ }
192
+ for (const store of stores) {
193
+ writeKey(store, TERRENO_AUTH_TOKEN_KEYS.authToken, authToken);
194
+ if (refreshToken !== undefined) {
195
+ writeKey(store, TERRENO_AUTH_TOKEN_KEYS.refreshToken, refreshToken);
196
+ }
197
+ }
198
+ };
@@ -0,0 +1,503 @@
1
+ import {mock} from "bun:test";
2
+ import {DateTime} from "luxon";
3
+
4
+ import {
5
+ type ExpoTestPlatform,
6
+ hostComponent,
7
+ type MockComponent,
8
+ type ModuleExports,
9
+ type ModuleMockMap,
10
+ passthroughComponent,
11
+ stub,
12
+ stubResolving,
13
+ stubReturning,
14
+ stubSubscription,
15
+ } from "./mockHelpers";
16
+
17
+ /** Options for the generated Expo module stand-ins. */
18
+ export interface ExpoModuleMockOptions {
19
+ /** `expo-constants` `expoConfig` (an app.json `expo` block). Default `{extra: {}, name: "test", slug: "test"}`. */
20
+ expoConfig?: Record<string, unknown>;
21
+ /** Locale reported by `expo-localization`. Default `"en-US"`. */
22
+ locale?: string;
23
+ /** Platform reported through `expo-modules-core` and `expo-device`. Default `"ios"`. */
24
+ platform?: ExpoTestPlatform;
25
+ /** Deep-link scheme `expo-linking.createURL` builds on. Default `expoConfig.scheme` or `"exp"`. */
26
+ scheme?: string;
27
+ /** IANA zone `expo-localization` reports. Default `"America/New_York"`. */
28
+ timeZone?: string;
29
+ }
30
+
31
+ /** Icon families mocked under `@expo/vector-icons` and `@expo/vector-icons/<Family>`. */
32
+ export const VECTOR_ICON_FAMILIES = [
33
+ "AntDesign",
34
+ "Entypo",
35
+ "EvilIcons",
36
+ "Feather",
37
+ "FontAwesome",
38
+ "FontAwesome5",
39
+ "FontAwesome6",
40
+ "Fontisto",
41
+ "Foundation",
42
+ "Ionicons",
43
+ "MaterialCommunityIcons",
44
+ "MaterialIcons",
45
+ "Octicons",
46
+ "SimpleLineIcons",
47
+ "Zocial",
48
+ ] as const;
49
+
50
+ const PERMISSION_STATUS = {
51
+ DENIED: "denied",
52
+ GRANTED: "granted",
53
+ UNDETERMINED: "undetermined",
54
+ } as const;
55
+
56
+ const GRANTED_PERMISSION = {canAskAgain: true, expires: "never", granted: true, status: "granted"};
57
+
58
+ /** Event emitter stand-in for `expo-modules-core`'s `EventEmitter` and the classes built on it. */
59
+ class MockEventEmitter {
60
+ addListener: ReturnType<typeof stubSubscription>;
61
+ emit: ReturnType<typeof stub>;
62
+ listenerCount: ReturnType<typeof stubReturning<number>>;
63
+ removeAllListeners: ReturnType<typeof stub>;
64
+ removeListener: ReturnType<typeof stub>;
65
+ removeSubscription: ReturnType<typeof stub>;
66
+
67
+ constructor() {
68
+ this.addListener = stubSubscription();
69
+ this.emit = stub();
70
+ this.listenerCount = stubReturning(0);
71
+ this.removeAllListeners = stub();
72
+ this.removeListener = stub();
73
+ this.removeSubscription = stub();
74
+ }
75
+ }
76
+
77
+ class MockNativeModule extends MockEventEmitter {}
78
+
79
+ class MockSharedObject extends MockEventEmitter {}
80
+
81
+ class MockSharedRef extends MockSharedObject {}
82
+
83
+ /** The `globalThis.expo` object `expo-modules-core` reads when it loads. */
84
+ export const createExpoGlobal = (): Record<string, unknown> => ({
85
+ EventEmitter: MockEventEmitter,
86
+ modules: {},
87
+ NativeModule: MockNativeModule,
88
+ SharedObject: MockSharedObject,
89
+ SharedRef: MockSharedRef,
90
+ });
91
+
92
+ class CodedError extends Error {
93
+ code: string;
94
+ constructor(code: string, message: string) {
95
+ super(message);
96
+ this.code = code;
97
+ }
98
+ }
99
+
100
+ class UnavailabilityError extends CodedError {
101
+ constructor(moduleName: string, propertyName: string) {
102
+ super("ERR_UNAVAILABLE", `${moduleName}.${propertyName} is not available in tests`);
103
+ }
104
+ }
105
+
106
+ /** A `createPermissionHook` stand-in: the hook reports a granted permission. */
107
+ const createPermissionHook = mock(() =>
108
+ mock(() => [
109
+ GRANTED_PERMISSION,
110
+ stubResolving(GRANTED_PERMISSION),
111
+ stubResolving(GRANTED_PERMISSION),
112
+ ])
113
+ );
114
+
115
+ /** Exports `expo` and `expo-modules-core` share: native module loaders return empty objects. */
116
+ const createNativeModuleCore = (platform: ExpoTestPlatform): ModuleExports => ({
117
+ CodedError,
118
+ createPermissionHook,
119
+ EventEmitter: MockEventEmitter,
120
+ LegacyEventEmitter: MockEventEmitter,
121
+ NativeModule: MockNativeModule,
122
+ NativeModulesProxy: {},
123
+ PermissionStatus: PERMISSION_STATUS,
124
+ Platform: {
125
+ OS: platform,
126
+ select: <T>(spec: Partial<Record<string, T>>): T | undefined => spec[platform] ?? spec.default,
127
+ },
128
+ registerWebModule: mock(<T>(moduleClass: T): T => moduleClass),
129
+ reloadAppAsync: stubResolving(undefined),
130
+ requireNativeModule: stubReturning({}),
131
+ requireNativeViewManager: stubReturning(hostComponent("NativeView")),
132
+ requireOptionalNativeModule: stubReturning(null),
133
+ SharedObject: MockSharedObject,
134
+ SharedRef: MockSharedRef,
135
+ UnavailabilityError,
136
+ useReleasingSharedObject: mock(<T>(factory: () => T): T => factory()),
137
+ uuid: {v4: stubReturning("00000000-0000-4000-8000-000000000000")},
138
+ });
139
+
140
+ const createRouterMock = (): ModuleExports => {
141
+ const createRouterHandle = (): Record<string, unknown> => ({
142
+ back: stub(),
143
+ canDismiss: stubReturning(false),
144
+ canGoBack: stubReturning(true),
145
+ dismiss: stub(),
146
+ dismissAll: stub(),
147
+ dismissTo: stub(),
148
+ navigate: stub(),
149
+ prefetch: stub(),
150
+ push: stub(),
151
+ replace: stub(),
152
+ setParams: stub(),
153
+ });
154
+ const navigatorWithScreen = (name: string): MockComponent =>
155
+ Object.assign(hostComponent(name), {Screen: hostComponent(`${name}.Screen`)});
156
+ const Navigator = Object.assign(hostComponent("Navigator"), {
157
+ Slot: hostComponent("Slot"),
158
+ useContext: stubReturning({
159
+ descriptors: {},
160
+ navigation: {},
161
+ router: {},
162
+ state: {index: 0, routes: []},
163
+ }),
164
+ });
165
+ const navigationFonts = {
166
+ bold: {fontFamily: "System", fontWeight: "600"},
167
+ heavy: {fontFamily: "System", fontWeight: "700"},
168
+ medium: {fontFamily: "System", fontWeight: "500"},
169
+ regular: {fontFamily: "System", fontWeight: "400"},
170
+ };
171
+ return {
172
+ DarkTheme: {
173
+ colors: {
174
+ background: "#010101",
175
+ border: "#272729",
176
+ card: "#121212",
177
+ notification: "#ff453a",
178
+ primary: "#0a84ff",
179
+ text: "#e5e5e7",
180
+ },
181
+ dark: true,
182
+ fonts: navigationFonts,
183
+ },
184
+ DefaultTheme: {
185
+ colors: {
186
+ background: "#f2f2f2",
187
+ border: "#d8d8d8",
188
+ card: "#ffffff",
189
+ notification: "#ff3b30",
190
+ primary: "#007aff",
191
+ text: "#1c1c1e",
192
+ },
193
+ dark: false,
194
+ fonts: navigationFonts,
195
+ },
196
+ Link: hostComponent("Link"),
197
+ Navigator,
198
+ Redirect: hostComponent("Redirect"),
199
+ router: createRouterHandle(),
200
+ Slot: hostComponent("Slot"),
201
+ Stack: navigatorWithScreen("Stack"),
202
+ Tabs: navigatorWithScreen("Tabs"),
203
+ ThemeProvider: passthroughComponent,
204
+ useFocusEffect: mock((effect?: () => unknown): void => {
205
+ effect?.();
206
+ }),
207
+ useGlobalSearchParams: stubReturning({}),
208
+ useLocalSearchParams: stubReturning({}),
209
+ useNavigation: mock(() => ({
210
+ addListener: stubReturning(stub()),
211
+ canGoBack: stubReturning(true),
212
+ dispatch: stub(),
213
+ getParent: stubReturning(undefined),
214
+ goBack: stub(),
215
+ isFocused: stubReturning(true),
216
+ navigate: stub(),
217
+ setOptions: stub(),
218
+ })),
219
+ useNavigationContainerRef: stubReturning({current: null}),
220
+ usePathname: stubReturning("/"),
221
+ useRootNavigationState: stubReturning({key: "root"}),
222
+ useRouter: mock(createRouterHandle),
223
+ useSearchParams: stubReturning({}),
224
+ useSegments: stubReturning([]),
225
+ };
226
+ };
227
+
228
+ const createVectorIconsMocks = (): ModuleMockMap => {
229
+ const mocks: ModuleMockMap = {};
230
+ const root: ModuleExports = {};
231
+ for (const family of VECTOR_ICON_FAMILIES) {
232
+ const Icon = Object.assign(hostComponent(family), {
233
+ getImageSource: stubResolving(null),
234
+ glyphMap: {},
235
+ loadFont: stubResolving(undefined),
236
+ });
237
+ root[family] = Icon;
238
+ mocks[`@expo/vector-icons/${family}`] = (): ModuleExports => ({default: Icon});
239
+ }
240
+ mocks["@expo/vector-icons"] = (): ModuleExports => ({
241
+ ...root,
242
+ createIconSet: stubReturning(hostComponent("Icon")),
243
+ });
244
+ return mocks;
245
+ };
246
+
247
+ /**
248
+ * Builds stand-ins for the Expo SDK modules most apps import: the `expo` / `expo-modules-core`
249
+ * native bridge, `expo-router`, `expo-constants`, `expo-linking`, `expo-font`, and the common
250
+ * device APIs. `expo-secure-store` lives in `authTokenStorage.ts`.
251
+ */
252
+ export const createExpoModuleMocks = ({
253
+ expoConfig = {extra: {}, name: "test", slug: "test"},
254
+ locale = "en-US",
255
+ platform = "ios",
256
+ scheme,
257
+ timeZone = "America/New_York",
258
+ }: ExpoModuleMockOptions = {}): ModuleMockMap => {
259
+ const linkingScheme =
260
+ scheme ?? (typeof expoConfig.scheme === "string" ? expoConfig.scheme : "exp");
261
+ const [languageCode = "en", regionCode = "US"] = locale.split("-");
262
+ const core = createNativeModuleCore(platform);
263
+ const noopModule = (): ModuleExports => ({});
264
+
265
+ return {
266
+ ...createVectorIconsMocks(),
267
+ expo: () => ({
268
+ ...core,
269
+ isRunningInExpoGo: stubReturning(false),
270
+ registerRootComponent: stub(),
271
+ useEvent: stubReturning(undefined),
272
+ useEventListener: stub(),
273
+ }),
274
+ "expo-application": () => ({
275
+ applicationId: "com.terreno.test",
276
+ applicationName: "test",
277
+ getInstallationTimeAsync: stubResolving(DateTime.fromMillis(0).toJSDate()),
278
+ nativeApplicationVersion: "1.0.0",
279
+ nativeBuildVersion: "1",
280
+ }),
281
+ "expo-asset": () => ({
282
+ Asset: {
283
+ fromModule: stubReturning({
284
+ downloadAsync: stubResolving(undefined),
285
+ localUri: "test-asset",
286
+ uri: "test-asset",
287
+ }),
288
+ loadAsync: stubResolving([]),
289
+ },
290
+ useAssets: stubReturning([[], undefined]),
291
+ }),
292
+ "expo-clipboard": () => ({
293
+ getStringAsync: stubResolving(""),
294
+ hasStringAsync: stubResolving(false),
295
+ setImageAsync: stubResolving(undefined),
296
+ setString: stub(),
297
+ setStringAsync: stubResolving(true),
298
+ }),
299
+ "expo-constants": () => {
300
+ const constants = {
301
+ appOwnership: null,
302
+ executionEnvironment: "bare",
303
+ expoConfig,
304
+ manifest: expoConfig,
305
+ platform: {[platform]: {}},
306
+ sessionId: "test-session",
307
+ statusBarHeight: 0,
308
+ };
309
+ return {
310
+ AppOwnership: {Expo: "expo"},
311
+ default: constants,
312
+ ExecutionEnvironment: {Bare: "bare", Standalone: "standalone", StoreClient: "storeClient"},
313
+ UserInterfaceIdiom: {
314
+ Desktop: "desktop",
315
+ Handset: "handset",
316
+ Tablet: "tablet",
317
+ TV: "tv",
318
+ Unsupported: "unsupported",
319
+ },
320
+ };
321
+ },
322
+ "expo-device": () => ({
323
+ brand: "Test",
324
+ DeviceType: {DESKTOP: 3, PHONE: 1, TABLET: 2, TV: 4, UNKNOWN: 0},
325
+ deviceType: 1,
326
+ getDeviceTypeAsync: stubResolving(1),
327
+ isDevice: false,
328
+ manufacturer: "Test",
329
+ modelName: "Test Device",
330
+ osName: platform === "android" ? "Android" : platform === "web" ? "Web" : "iOS",
331
+ osVersion: "1.0",
332
+ }),
333
+ "expo-file-system": () => ({
334
+ cacheDirectory: "file:///cache/",
335
+ deleteAsync: stubResolving(undefined),
336
+ documentDirectory: "file:///documents/",
337
+ File: class File {
338
+ bytes = stubResolving(new Uint8Array());
339
+ exists = false;
340
+ text = stubResolving("");
341
+ uri: string;
342
+ constructor(...parts: unknown[]) {
343
+ this.uri = parts.map(String).join("/");
344
+ }
345
+ },
346
+ getInfoAsync: stubResolving({exists: false, isDirectory: false}),
347
+ readAsStringAsync: stubResolving(""),
348
+ writeAsStringAsync: stubResolving(undefined),
349
+ }),
350
+ "expo-font": () => ({
351
+ isLoaded: stubReturning(true),
352
+ isLoading: stubReturning(false),
353
+ loadAsync: stubResolving(undefined),
354
+ useFonts: stubReturning([true, null]),
355
+ }),
356
+ "expo-haptics": () => ({
357
+ ImpactFeedbackStyle: {
358
+ Heavy: "heavy",
359
+ Light: "light",
360
+ Medium: "medium",
361
+ Rigid: "rigid",
362
+ Soft: "soft",
363
+ },
364
+ impactAsync: stubResolving(undefined),
365
+ NotificationFeedbackType: {Error: "error", Success: "success", Warning: "warning"},
366
+ notificationAsync: stubResolving(undefined),
367
+ selectionAsync: stubResolving(undefined),
368
+ }),
369
+ "expo-image-manipulator": () => ({
370
+ ImageManipulator: {
371
+ manipulate: stubReturning({
372
+ renderAsync: stubResolving({saveAsync: stubResolving({height: 0, uri: "", width: 0})}),
373
+ }),
374
+ },
375
+ manipulateAsync: stubResolving({height: 0, uri: "", width: 0}),
376
+ SaveFormat: {JPEG: "jpeg", PNG: "png", WEBP: "webp"},
377
+ }),
378
+ "expo-image-picker": () => ({
379
+ launchCameraAsync: stubResolving({assets: null, canceled: true}),
380
+ launchImageLibraryAsync: stubResolving({assets: null, canceled: true}),
381
+ MediaTypeOptions: {All: "All", Images: "Images", Videos: "Videos"},
382
+ PermissionStatus: PERMISSION_STATUS,
383
+ requestCameraPermissionsAsync: stubResolving(GRANTED_PERMISSION),
384
+ requestMediaLibraryPermissionsAsync: stubResolving(GRANTED_PERMISSION),
385
+ useCameraPermissions: createPermissionHook(),
386
+ useMediaLibraryPermissions: createPermissionHook(),
387
+ }),
388
+ "expo-linear-gradient": () => ({LinearGradient: hostComponent("LinearGradient")}),
389
+ "expo-linking": () => {
390
+ const createURL = mock(
391
+ (path = "", options?: {queryParams?: Record<string, string>}): string => {
392
+ const query = new URLSearchParams(options?.queryParams ?? {}).toString();
393
+ return `${linkingScheme}://${path.replace(/^\//u, "")}${query ? `?${query}` : ""}`;
394
+ }
395
+ );
396
+ return {
397
+ addEventListener: stubSubscription(),
398
+ canOpenURL: stubResolving(true),
399
+ createURL,
400
+ getInitialURL: stubResolving(null),
401
+ getLinkingURL: stubReturning(null),
402
+ openSettings: stubResolving(undefined),
403
+ openURL: stubResolving(true),
404
+ parse: mock((url: string) => ({
405
+ hostname: null,
406
+ path: url,
407
+ queryParams: {},
408
+ scheme: linkingScheme,
409
+ })),
410
+ parseInitialURLAsync: stubResolving({
411
+ hostname: null,
412
+ path: null,
413
+ queryParams: {},
414
+ scheme: null,
415
+ }),
416
+ resolveScheme: stubReturning(linkingScheme),
417
+ useLinkingURL: stubReturning(null),
418
+ useURL: stubReturning(null),
419
+ };
420
+ },
421
+ "expo-localization": () => ({
422
+ getCalendars: stubReturning([
423
+ {calendar: "gregorian", firstWeekday: 1, timeZone, uses24hourClock: false},
424
+ ]),
425
+ getLocales: stubReturning([
426
+ {
427
+ currencyCode: "USD",
428
+ decimalSeparator: ".",
429
+ digitGroupingSeparator: ",",
430
+ languageCode,
431
+ languageTag: locale,
432
+ measurementSystem: "us",
433
+ regionCode,
434
+ temperatureUnit: "fahrenheit",
435
+ textDirection: "ltr",
436
+ },
437
+ ]),
438
+ locale,
439
+ locales: [locale],
440
+ timezone: timeZone,
441
+ useCalendars: stubReturning([
442
+ {calendar: "gregorian", firstWeekday: 1, timeZone, uses24hourClock: false},
443
+ ]),
444
+ useLocales: stubReturning([{languageCode, languageTag: locale, regionCode}]),
445
+ }),
446
+ "expo-modules-core": () => core,
447
+ "expo-modules-core/src/Refs": () => ({createRef: stubReturning({current: null})}),
448
+ "expo-modules-core/src/uuid/uuid.web": () => ({
449
+ uuid4: stubReturning("00000000-0000-4000-8000-000000000000"),
450
+ }),
451
+ "expo-modules-core/src/web/index.web": () => ({EventEmitter: MockEventEmitter}),
452
+ "expo-network": () => ({
453
+ addNetworkStateListener: stubSubscription(),
454
+ getNetworkStateAsync: stubResolving({
455
+ isConnected: true,
456
+ isInternetReachable: true,
457
+ type: "WIFI",
458
+ }),
459
+ NetworkStateType: {CELLULAR: "CELLULAR", NONE: "NONE", UNKNOWN: "UNKNOWN", WIFI: "WIFI"},
460
+ useNetworkState: stubReturning({isConnected: true, isInternetReachable: true, type: "WIFI"}),
461
+ }),
462
+ "expo-router": createRouterMock,
463
+ "expo-splash-screen": () => ({
464
+ hide: stub(),
465
+ hideAsync: stubResolving(true),
466
+ preventAutoHideAsync: stubResolving(true),
467
+ setOptions: stub(),
468
+ }),
469
+ "expo-status-bar": () => ({
470
+ StatusBar: hostComponent("ExpoStatusBar"),
471
+ setStatusBarStyle: stub(),
472
+ }),
473
+ "expo-updates": () => ({
474
+ channel: "test",
475
+ checkForUpdateAsync: stubResolving({isAvailable: false}),
476
+ fetchUpdateAsync: stubResolving({isNew: false}),
477
+ isEnabled: false,
478
+ reloadAsync: stubResolving(undefined),
479
+ updateId: null,
480
+ useUpdates: stubReturning({isUpdateAvailable: false, isUpdatePending: false}),
481
+ }),
482
+ "expo-web-browser": () => ({
483
+ dismissBrowser: stub(),
484
+ maybeCompleteAuthSession: stubReturning({type: "failed"}),
485
+ openAuthSessionAsync: stubResolving({type: "cancel"}),
486
+ openBrowserAsync: stubResolving({type: "opened"}),
487
+ WebBrowserResultType: {
488
+ CANCEL: "cancel",
489
+ DISMISS: "dismiss",
490
+ LOCKED: "locked",
491
+ OPENED: "opened",
492
+ },
493
+ }),
494
+ "expo/src/async-require/hmr": () => ({
495
+ default: {disable: stub(), enable: stub(), log: stub(), setup: stub()},
496
+ }),
497
+ "expo/src/async-require/messageSocket": noopModule,
498
+ "expo/src/async-require/setupHMR": noopModule,
499
+ // Expo's dev-only HMR client touches `window`/`document` when it loads.
500
+ "expo/src/Expo.fx": noopModule,
501
+ "expo/src/Expo.fx.tsx": noopModule,
502
+ };
503
+ };