Files
faunosteo/apps/app/tests/helpers/fakeSupabase.ts
T
bchanot 926dd7df8c feat(app): profile photo — avatar upload in Mon compte, photo in the sidebar, drawer and top bar
packages/supabase assets module: closed AssetFailure kinds, begin / quarantine
upload (upsert off) / confirm / remove, own-row state read with an explicit
column list, download under the SELECT policy. App: client transport (magic
byte sniff, never SVG, createImageBitmap, canvas 1024 px, JPEG 0.9, 5 MiB
cap), AvatarSection (preview, save, 1 s polling up to 30 s, rejection and
failure messages per closed code, removal with confirmation, in-flight row
resumed at mount), auth store blob URL revoked on change and sign-out,
AvatarCircle in UserBadge and the top bar link to Mon compte (D3), FR/EN
strings, fake client extended, 27 new tests (app 300).
2026-10-13 19:32:37 +02:00

214 lines
6.2 KiB
TypeScript

/**
* In-memory stand-in for the parts of the Supabase client the identity and
* files steps use: auth events, profile select/update, profile_roles and
* assets selects, rpc, storage upload / download. Tests mock
* `@/lib/supabase` to hand this object out.
*/
import { vi } from 'vitest'
import type {
AssetRow,
AuthChangeEvent,
FaunosteoClient,
Profile,
Session,
User,
} from '@faunosteo/supabase'
type Listener = (event: AuthChangeEvent, session: Session | null) => void
type Row = Record<string, unknown>
export function fakeUser(patch: Partial<User> = {}): User {
return {
id: 'user-1',
aud: 'authenticated',
email: 'alice@example.test',
email_confirmed_at: '2026-10-11T10:00:00Z',
created_at: '2026-10-01T10:00:00Z',
app_metadata: {},
user_metadata: {},
...patch,
} as User
}
export function fakeSession(user: User = fakeUser()): Session {
return {
access_token: 'at',
refresh_token: 'rt',
token_type: 'bearer',
expires_in: 3600,
user,
} as Session
}
export function fakeProfile(patch: Partial<Profile> = {}): Profile {
return {
id: 'user-1',
display_name: 'Alice Local',
first_name: null,
last_name: null,
phone: null,
phone_verified_at: null,
locale: 'fr',
timezone: 'Europe/Paris',
active: true,
practice_name: null,
professional_title: null,
siret: null,
created_at: '2026-10-01T10:00:00Z',
updated_at: '2026-10-01T10:00:00Z',
...patch,
}
}
export function fakeAssetRow(patch: Partial<AssetRow> = {}): AssetRow {
return {
id: 'asset-1',
owner_id: 'user-1',
kind: 'profile_avatar',
bucket_id: 'avatars',
object_key: 'profiles/user-1/asset-1/avatar.webp',
status: 'clean',
declared_mime: 'image/jpeg',
declared_size: 1000,
byte_size: 900,
sha256: null,
rejection_reason: null,
created_at: '2026-10-13T10:00:00Z',
updated_at: '2026-10-13T10:00:00Z',
...patch,
}
}
/** Minimal PostgREST builder: filters, order, limit, then select / update, awaitable. */
function builder(tables: Record<string, Row[]>, table: string) {
const filters: Array<(row: Row) => boolean> = []
let patch: Row | null = null
let order: { col: string; ascending: boolean } | null = null
let max: number | null = null
const rows = () => {
let hit = (tables[table] ?? []).filter((r) => filters.every((f) => f(r)))
if (order) {
const { col, ascending } = order
hit = [...hit].sort((a, b) =>
(String(a[col]) < String(b[col]) ? -1 : String(a[col]) > String(b[col]) ? 1 : 0) *
(ascending ? 1 : -1),
)
}
return max === null ? hit : hit.slice(0, max)
}
const apply = () => {
if (!patch) return rows()
const hit = rows()
hit.forEach((r) => Object.assign(r, patch))
return hit
}
const api = {
select: () => api,
update: (values: Row) => {
patch = values
return api
},
eq: (col: string, value: unknown) => {
filters.push((r) => r[col] === value)
return api
},
is: (col: string, value: unknown) => {
filters.push((r) => r[col] === value)
return api
},
in: (col: string, values: unknown[]) => {
filters.push((r) => values.includes(r[col]))
return api
},
order: (col: string, opts?: { ascending?: boolean }) => {
order = { col, ascending: opts?.ascending ?? true }
return api
},
limit: (n: number) => {
max = n
return api
},
maybeSingle: async () => ({ data: apply()[0] ?? null, error: null }),
single: async () => {
const [first] = apply()
return first
? { data: first, error: null }
: { data: null, error: { message: 'no row', code: 'PGRST116' } }
},
then: (resolve: (v: { data: Row[]; error: null }) => void) =>
resolve({ data: apply(), error: null }),
}
return api
}
export interface FakeSupabase {
client: FaunosteoClient
tables: Record<string, Row[]>
emit: (event: AuthChangeEvent, session: Session | null) => void
/** Recorded rpc calls; program results with `rpcResults[name]`. */
rpcCalls: Array<[string, unknown]>
rpcResults: Record<string, { data?: unknown; error?: unknown } | (() => { data?: unknown; error?: unknown })>
storage: {
upload: ReturnType<typeof vi.fn>
download: ReturnType<typeof vi.fn>
}
auth: {
initialize: ReturnType<typeof vi.fn>
signInWithPassword: ReturnType<typeof vi.fn>
signUp: ReturnType<typeof vi.fn>
signOut: ReturnType<typeof vi.fn>
updateUser: ReturnType<typeof vi.fn>
resetPasswordForEmail: ReturnType<typeof vi.fn>
signInWithOAuth: ReturnType<typeof vi.fn>
}
}
export function createFakeSupabase(
tables: Record<string, Row[]> = { profiles: [fakeProfile()], profile_roles: [], assets: [] },
): FakeSupabase {
tables.assets ??= []
const listeners: Listener[] = []
const rpcCalls: Array<[string, unknown]> = []
const rpcResults: FakeSupabase['rpcResults'] = {}
const storage = {
upload: vi.fn(async () => ({ data: null, error: null })),
download: vi.fn(async () => ({ data: new Blob([new Uint8Array([82, 73, 70, 70])]), error: null })),
}
const auth = {
initialize: vi.fn(async () => ({ error: null })),
onAuthStateChange: vi.fn((cb: Listener) => {
listeners.push(cb)
return { data: { subscription: { unsubscribe: vi.fn() } } }
}),
signInWithPassword: vi.fn(),
signUp: vi.fn(),
signOut: vi.fn(async () => ({ error: null })),
updateUser: vi.fn(),
resetPasswordForEmail: vi.fn(),
signInWithOAuth: vi.fn(),
}
const client = {
auth,
from: (table: string) => builder(tables, table),
rpc: async (name: string, args?: unknown) => {
rpcCalls.push([name, args])
const entry = rpcResults[name]
const result = typeof entry === 'function' ? entry() : (entry ?? {})
return { data: result.data ?? null, error: result.error ?? null }
},
storage: { from: () => storage },
} as unknown as FaunosteoClient
return {
client,
tables,
auth,
rpcCalls,
rpcResults,
storage,
emit: (event, session) => listeners.forEach((cb) => cb(event, session)),
}
}
/** Resolves once the store has run its deferred account load. */
export const flush = () => new Promise((r) => setTimeout(r, 0))