Skip to content

Commit 2e617bd

Browse files
chore: stub cache server in vitest
Co-authored-by: me <me@kentcdodds.com>
1 parent d8d4223 commit 2e617bd

2 files changed

Lines changed: 67 additions & 0 deletions

File tree

tests/mocks/cache-server.ts

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
type CacheEntry<Value> = {
2+
metadata: {
3+
createdTime: number
4+
ttl?: number | null
5+
swr?: number | null
6+
}
7+
value: Value
8+
}
9+
10+
const lruStore = new Map<string, CacheEntry<unknown>>()
11+
const sqliteStore = new Map<string, CacheEntry<unknown>>()
12+
13+
export const lruCache = {
14+
name: 'test-lru-cache',
15+
set: (key: string, value: CacheEntry<unknown>) => {
16+
lruStore.set(key, value)
17+
return value
18+
},
19+
get: (key: string) => lruStore.get(key),
20+
delete: (key: string) => lruStore.delete(key),
21+
}
22+
23+
export const cache = {
24+
name: 'test-sqlite-cache',
25+
async get(key: string) {
26+
return sqliteStore.get(key) ?? null
27+
},
28+
async set(key: string, entry: CacheEntry<unknown>) {
29+
sqliteStore.set(key, entry)
30+
return entry
31+
},
32+
async delete(key: string) {
33+
sqliteStore.delete(key)
34+
},
35+
}
36+
37+
export async function getAllCacheKeys(limit: number) {
38+
const sqlite = [...sqliteStore.keys()].slice(0, limit)
39+
const lru = [...lruStore.keys()].slice(0, limit)
40+
return { sqlite, lru }
41+
}
42+
43+
export async function searchCacheKeys(search: string, limit: number) {
44+
const matches = (value: string) => value.includes(search)
45+
const sqlite = [...sqliteStore.keys()].filter(matches).slice(0, limit)
46+
const lru = [...lruStore.keys()].filter(matches).slice(0, limit)
47+
return { sqlite, lru }
48+
}
49+
50+
export async function cachified<Value>(
51+
options: {
52+
getFreshValue: () => Promise<Value> | Value
53+
},
54+
): Promise<Value> {
55+
return options.getFreshValue()
56+
}

vite.config.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import path from 'node:path'
12
import { reactRouter } from '@react-router/dev/vite'
23
import {
34
type SentryReactRouterBuildOptions,
@@ -37,6 +38,16 @@ export default defineConfig((config) => ({
3738
ignored: ['**/playwright-report/**'],
3839
},
3940
},
41+
resolve: {
42+
alias:
43+
MODE === 'test'
44+
? {
45+
'#app/utils/cache.server.ts': path.resolve(
46+
'tests/mocks/cache-server.ts',
47+
),
48+
}
49+
: {},
50+
},
4051
sentryConfig,
4152
plugins: [
4253
envOnlyMacros(),

0 commit comments

Comments
 (0)