From 15b4bdc8106360d6c8e10b126af6016af53a0c57 Mon Sep 17 00:00:00 2001 From: Samuel Newman Date: Mon, 29 Jun 2026 18:39:07 +0300 Subject: [PATCH] stub async-storage for vitest to fix unhandled window error --- vitest.config.ts | 9 +++++++++ vitest/async-storage-stub.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 vitest/async-storage-stub.ts diff --git a/vitest.config.ts b/vitest.config.ts index a0472c3bb1..aa30227605 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -120,6 +120,15 @@ export default defineConfig({ */ {find: /^expo$/, replacement: r('./vitest/expo-stub.ts')}, + /* + * async-storage references `window` at module load, undefined under + * node. Stubbed with an in-memory implementation. + */ + { + find: /^@react-native-async-storage\/async-storage$/, + replacement: r('./vitest/async-storage-stub.ts'), + }, + /* * Former Jest moduleNameMapper entries. Vite's ESM resolution may make * some of these unnecessary, but they're harmless and proven, so keep diff --git a/vitest/async-storage-stub.ts b/vitest/async-storage-stub.ts new file mode 100644 index 0000000000..89fc41a268 --- /dev/null +++ b/vitest/async-storage-stub.ts @@ -0,0 +1,27 @@ +/* + * Stub for @react-native-async-storage/async-storage. The real package + * references `window` at module load, which is undefined in Vitest's node + * environment. The package ships an official jest mock, but it relies on the + * `jest` global, so we provide a small in-memory implementation instead. + * + * Aliased in place of @react-native-async-storage/async-storage via + * resolve.alias in vitest.config.ts. Test-reachable code only uses + * getItem/setItem/removeItem. + */ +const store = new Map() + +const AsyncStorage = { + getItem(key: string): Promise { + return Promise.resolve(store.has(key) ? store.get(key)! : null) + }, + setItem(key: string, value: string): Promise { + store.set(key, value) + return Promise.resolve() + }, + removeItem(key: string): Promise { + store.delete(key) + return Promise.resolve() + }, +} + +export default AsyncStorage