test(app): identity step — auth store, locale sync, login/signup, guards, shell, dashboard, account

- tests/helpers/fakeSupabase: in-memory auth events + profiles/profile_roles builder
- validation schemas and safeNextPath; classifyAuthError mapping (packages/supabase)
- LoginRoute (unavailable, validation, next path, phrased failure, OAuth buttons, show password)
- SignupRoute (policy, mismatch, metadata + redirect, user exists)
- RequireAuth / RedirectIfSignedIn, AppLayout (nav, active, drawer, sign out), Dashboard, Account forms
This commit is contained in:
bchanot committed 2026-10-11 23:33:25 +02:00
1 parent c517ea267b
commit aa1985eead
11 files changed
+993

No files matched your search

+144
View File
@@ -0,0 +1,144 @@
/**
* In-memory stand-in for the parts of the Supabase client the identity step
* uses: auth events, profile select/update, profile_roles select. Tests mock
* `@/lib/supabase` to hand this object out.
*/
import { vi } from 'vitest'
import type {
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,
}
}
/** Minimal PostgREST builder: filters, then select / update, awaitable. */
function builder(tables: Record<string, Row[]>, table: string) {
const filters: Array<(row: Row) => boolean> = []
let patch: Row | null = null
const rows = () => (tables[table] ?? []).filter((r) => filters.every((f) => f(r)))
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
},
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
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: [] },
): FakeSupabase {
const listeners: Listener[] = []
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),
} as unknown as FaunosteoClient
return {
client,
tables,
auth,
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))
+115
View File
@@ -0,0 +1,115 @@
import { describe, expect, it } from 'vitest'
import {
fieldErrors,
loginSchema,
newPasswordSchema,
passwordSchema,
signupSchema,
} from '@/auth/validation'
import { safeNextPath } from '@/auth/redirects'
import {
personalPatch,
personalSchema,
professionalSchema,
translateFieldError,
} from '@/account/validation'
describe('auth validation', () => {
it('password mirrors the server policy: 12 chars, lower, upper, digit', () => {
expect(passwordSchema.safeParse('Short1aA').success).toBe(false)
expect(passwordSchema.safeParse('alllowercase123').success).toBe(false)
expect(passwordSchema.safeParse('NoDigitsHereAtAll').success).toBe(false)
expect(passwordSchema.safeParse('CorrectHorse12').success).toBe(true)
})
it('reports one i18n key per field, first issue wins', () => {
const r = loginSchema.safeParse({ email: 'nope', password: '' })
expect(r.success).toBe(false)
if (!r.success) {
expect(fieldErrors(r.error)).toEqual({
email: 'auth.error.email_invalid',
password: 'auth.error.password_required',
})
}
})
it('signup flags a confirmation mismatch on the confirm field', () => {
const r = signupSchema.safeParse({
displayName: 'A',
email: 'a@b.co',
password: 'CorrectHorse12',
passwordConfirm: 'CorrectHorse13',
})
expect(r.success).toBe(false)
if (!r.success) {
expect(fieldErrors(r.error).passwordConfirm).toBe('auth.error.password_mismatch')
}
expect(
newPasswordSchema.safeParse({ password: 'CorrectHorse12', passwordConfirm: 'x' })
.success,
).toBe(false)
})
})
describe('safeNextPath', () => {
it('keeps same-origin paths and refuses anything else', () => {
expect(safeNextPath('/app/account')).toBe('/app/account')
expect(safeNextPath(null)).toBe('/app')
expect(safeNextPath('https://evil.test/')).toBe('/app')
expect(safeNextPath('//evil.test')).toBe('/app')
expect(safeNextPath('app')).toBe('/app')
})
})
describe('account validation', () => {
it('turns empty optional fields into null and keeps display_name', () => {
const r = personalSchema.safeParse({
display_name: ' Alice ',
first_name: '',
last_name: 'Local',
phone: '',
})
expect(r.success).toBe(true)
if (r.success) {
expect(personalPatch(r.data)).toEqual({
display_name: 'Alice',
first_name: null,
last_name: 'Local',
phone: null,
})
}
})
it('checks phone E.164 and SIRET 14 digits (spaces tolerated)', () => {
const bad = personalSchema.safeParse({
display_name: 'A',
first_name: '',
last_name: '',
phone: '06 12',
})
expect(bad.success).toBe(false)
const siretOk = professionalSchema.safeParse({
professional_title: '',
practice_name: '',
siret: '123 456 789 01234',
})
expect(siretOk.success).toBe(true)
if (siretOk.success) expect(siretOk.data.siret).toBe('12345678901234')
const siretBad = professionalSchema.safeParse({
professional_title: '',
practice_name: '',
siret: '1234',
})
expect(siretBad.success).toBe(false)
if (!siretBad.success) {
expect(fieldErrors(siretBad.error).siret).toBe('account.error.siret_format')
}
})
it('translates a key|value message with its placeholder', () => {
const t = (k: string) => (k === 'account.error.too_long' ? 'Max {max}' : k)
expect(translateFieldError(t, 'account.error.too_long|80')).toBe('Max 80')
expect(translateFieldError(t, 'account.error.required')).toBe('account.error.required')
expect(translateFieldError(t, undefined)).toBeUndefined()
})
})
@@ -0,0 +1,75 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import RequireAuth from '@/app/guards/RequireAuth'
import RedirectIfSignedIn from '@/app/guards/RedirectIfSignedIn'
import { useAuthStore, type AuthStatus } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
function ShowLocation() {
const loc = useLocation()
return <p>{loc.pathname + loc.search}</p>
}
function mount(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/login" element={<ShowLocation />} />
<Route element={<RedirectIfSignedIn />}>
<Route path="/signup" element={<p>signup form</p>} />
</Route>
<Route path="/app" element={<RequireAuth />}>
<Route index element={<p>dashboard</p>} />
<Route path="account" element={<p>account</p>} />
</Route>
</Routes>
</MemoryRouter>,
)
}
function setStatus(status: AuthStatus) {
useAuthStore.setState({ status, recovery: false })
}
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
describe('RequireAuth', () => {
it('waits while the session loads', () => {
setStatus('loading')
mount('/app')
expect(screen.getByText(fr['shell.loading_session'])).toBeInTheDocument()
})
it('sends a visitor to /login with the return path', () => {
setStatus('signed_out')
mount('/app/account?tab=x')
expect(screen.getByText('/login?next=%2Fapp%2Faccount%3Ftab%3Dx')).toBeInTheDocument()
})
it('also redirects when no backend exists', () => {
setStatus('unavailable')
mount('/app')
expect(screen.getByText(/^\/login/)).toBeInTheDocument()
})
it('renders the page once signed in', () => {
setStatus('signed_in')
mount('/app/account')
expect(screen.getByText('account')).toBeInTheDocument()
})
})
describe('RedirectIfSignedIn', () => {
it('shows the form to a visitor and skips it for a signed-in user', () => {
setStatus('signed_out')
mount('/signup')
expect(screen.getByText('signup form')).toBeInTheDocument()
cleanup()
setStatus('signed_in')
mount('/signup')
expect(screen.queryByText('signup form')).not.toBeInTheDocument()
})
})
@@ -0,0 +1,101 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import AccountRoute from '@/app/routes/app/AccountRoute'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile(),
roles: ['owner'],
})
})
afterEach(cleanup)
function mount() {
return render(
<MemoryRouter>
<AccountRoute />
</MemoryRouter>,
)
}
describe('AccountRoute', () => {
it('shows the four sections, the roles and the sign-in address', () => {
mount()
for (const key of [
'account.personal.title',
'account.professional.title',
'account.preferences.title',
'account.security.title',
]) {
expect(screen.getByRole('heading', { name: fr[key] })).toBeInTheDocument()
}
expect(screen.getByText(fr['shell.role.owner'])).toBeInTheDocument()
expect(screen.getByText('alice@example.test')).toBeInTheDocument()
expect(screen.getByText(fr['account.security.mfa_note'])).toBeInTheDocument()
})
it('saves personal information, empty optionals as null', async () => {
const user = userEvent.setup()
mount()
await user.type(screen.getByLabelText(new RegExp(`^${fr['account.personal.first_name']}`)), 'Alice')
const [save] = screen.getAllByRole('button', { name: fr['account.save'] })
await user.click(save)
expect(await screen.findByText(fr['account.saved'])).toBeInTheDocument()
expect(fake.tables.profiles[0]).toMatchObject({
display_name: 'Alice Local',
first_name: 'Alice',
last_name: null,
phone: null,
})
})
it('refuses a malformed SIRET next to the field, without calling the server', async () => {
const user = userEvent.setup()
mount()
await user.type(screen.getByLabelText(new RegExp(`^${fr['account.professional.siret']}`)), '1234')
const saves = screen.getAllByRole('button', { name: fr['account.save'] })
await user.click(saves[1])
expect(await screen.findByText(fr['account.error.siret_format'])).toBeInTheDocument()
expect(fake.tables.profiles[0].siret).toBeNull()
})
it('changes the password through the client', async () => {
fake.auth.updateUser.mockResolvedValue({ data: {}, error: null })
const user = userEvent.setup()
mount()
await user.type(screen.getByLabelText(fr['account.security.new_password']), 'CorrectHorse12')
await user.type(screen.getByLabelText(fr['auth.password_confirm']), 'CorrectHorse12')
await user.click(screen.getByRole('button', { name: fr['account.security.change_password'] }))
await waitFor(() =>
expect(fake.auth.updateUser).toHaveBeenCalledWith({ password: 'CorrectHorse12' }),
)
expect(await screen.findByText(fr['account.security.password_changed'])).toBeInTheDocument()
})
it('switching the language select updates the locale store', async () => {
const user = userEvent.setup()
mount()
await user.selectOptions(screen.getByLabelText(fr['account.preferences.language']), 'en')
expect(useLocaleStore.getState().locale).toBe('en')
})
})
@@ -0,0 +1,58 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import DashboardRoute from '@/app/routes/app/DashboardRoute'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { fakeProfile, fakeUser } from '../helpers/fakeSupabase'
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
function mount() {
return render(
<MemoryRouter>
<DashboardRoute />
</MemoryRouter>,
)
}
describe('DashboardRoute', () => {
it('greets by first name and lists what the profile lacks', () => {
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile({ first_name: 'Alice' }),
roles: [],
})
mount()
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Bonjour Alice')
expect(screen.getByText(fr['dashboard.profile.incomplete'])).toBeInTheDocument()
expect(screen.getByText(fr['account.personal.last_name'], { exact: false })).toBeInTheDocument()
expect(
screen.getByRole('link', { name: fr['dashboard.profile.cta_complete'] }),
).toHaveAttribute('href', '/app/account')
expect(screen.getByText(fr['dashboard.account.verified'])).toBeInTheDocument()
expect(screen.getByText(fr['dashboard.account.no_roles'])).toBeInTheDocument()
})
it('switches to the complete state and shows roles', () => {
useAuthStore.setState({
status: 'signed_in',
user: fakeUser({ email_confirmed_at: undefined }),
profile: fakeProfile({
first_name: 'Alice',
last_name: 'Local',
professional_title: 'Ostéopathe',
practice_name: 'Cabinet',
}),
roles: ['admin'],
})
mount()
expect(screen.getByText(fr['dashboard.profile.complete'])).toBeInTheDocument()
expect(screen.getByRole('link', { name: fr['dashboard.profile.cta_view'] })).toBeInTheDocument()
expect(screen.getByText(fr['shell.role.admin'])).toBeInTheDocument()
expect(screen.getByText(fr['dashboard.account.unverified'])).toBeInTheDocument()
})
})
@@ -0,0 +1,124 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { createFakeSupabase, fakeSession, type FakeSupabase } from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown, providers: [] as string[] }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
vi.mock('@/app/providers/ConfigProvider', async (importOriginal) => {
const mod = await importOriginal<typeof import('@/app/providers/ConfigProvider')>()
return {
...mod,
useConfig: () => ({
siteName: 'Faunosteo',
brandName: 'Faunosteo',
footerName: 'Faunosteo',
tagline: 'T',
supabase: mocks.fake ? { url: 'http://x', anonKey: 'k' } : null,
authProviders: mocks.providers,
}),
}
})
import LoginRoute from '@/app/routes/auth/LoginRoute'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useAuthStore.setState({ status: 'signed_out', recovery: false })
fake = createFakeSupabase()
mocks.fake = fake
mocks.providers = []
})
afterEach(cleanup)
function mount(path = '/login') {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/login" element={<LoginRoute />} />
<Route path="/app" element={<p>dashboard</p>} />
<Route path="/app/account" element={<p>account</p>} />
</Routes>
</MemoryRouter>,
)
}
describe('LoginRoute', () => {
it('explains when no backend is configured', () => {
mocks.fake = null
mount()
expect(screen.getByText(fr['auth.unavailable_title'])).toBeInTheDocument()
expect(screen.queryByLabelText(fr['auth.email'])).not.toBeInTheDocument()
})
it('validates before calling the server', async () => {
const user = userEvent.setup()
mount()
await user.click(screen.getByRole('button', { name: fr['auth.login.submit'] }))
expect(screen.getByText(fr['auth.error.email_required'])).toBeInTheDocument()
expect(screen.getByText(fr['auth.error.password_required'])).toBeInTheDocument()
expect(fake.auth.signInWithPassword).not.toHaveBeenCalled()
})
it('signs in and follows the next path', async () => {
fake.auth.signInWithPassword.mockResolvedValue({
data: { session: fakeSession(), user: fakeSession().user },
error: null,
})
const user = userEvent.setup()
mount('/login?next=%2Fapp%2Faccount')
await user.type(screen.getByLabelText(fr['auth.email']), 'alice@example.test')
await user.type(screen.getByLabelText(fr['auth.password']), 'CorrectHorse12')
await user.click(screen.getByRole('button', { name: fr['auth.login.submit'] }))
await waitFor(() => expect(screen.getByText('account')).toBeInTheDocument())
expect(fake.auth.signInWithPassword).toHaveBeenCalledWith({
email: 'alice@example.test',
password: 'CorrectHorse12',
})
})
it('phrases a wrong password without leaking the server message', async () => {
fake.auth.signInWithPassword.mockResolvedValue({
data: { session: null, user: null },
error: { code: 'invalid_credentials', message: 'Invalid login credentials', status: 400 },
})
const user = userEvent.setup()
mount()
await user.type(screen.getByLabelText(fr['auth.email']), 'alice@example.test')
await user.type(screen.getByLabelText(fr['auth.password']), 'wrong')
await user.click(screen.getByRole('button', { name: fr['auth.login.submit'] }))
expect(
await screen.findByText(fr['auth.failure.invalid_credentials']),
).toBeInTheDocument()
expect(screen.queryByText(/Invalid login/)).not.toBeInTheDocument()
})
it('shows one OAuth button per configured provider', () => {
mocks.providers = ['google']
mount()
expect(
screen.getByRole('button', { name: fr['auth.continue_with_google'] }),
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: fr['auth.continue_with_apple'] }),
).not.toBeInTheDocument()
})
it('toggles password visibility', async () => {
const user = userEvent.setup()
mount()
const input = screen.getByLabelText(fr['auth.password'])
expect(input).toHaveAttribute('type', 'password')
await user.click(screen.getByRole('button', { name: fr['auth.show_password'] }))
expect(input).toHaveAttribute('type', 'text')
})
})
@@ -0,0 +1,84 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { createFakeSupabase, type FakeSupabase } from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import SignupRoute from '@/app/routes/auth/SignupRoute'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
})
afterEach(cleanup)
function mount() {
return render(
<MemoryRouter initialEntries={['/signup']}>
<SignupRoute />
</MemoryRouter>,
)
}
async function fill(user: ReturnType<typeof userEvent.setup>, password: string, confirm = password) {
await user.type(screen.getByLabelText(fr['auth.signup.display_name']), 'Alice')
await user.type(screen.getByLabelText(fr['auth.email']), 'alice@example.test')
await user.type(screen.getByLabelText(fr['auth.password']), password)
await user.type(screen.getByLabelText(fr['auth.password_confirm']), confirm)
await user.click(screen.getByRole('button', { name: fr['auth.signup.submit'] }))
}
describe('SignupRoute', () => {
it('enforces the password policy and the confirmation client-side', async () => {
const user = userEvent.setup()
mount()
await fill(user, 'weak', 'weak')
expect(screen.getByText(fr['auth.error.password_rules'])).toBeInTheDocument()
expect(fake.auth.signUp).not.toHaveBeenCalled()
cleanup()
mount()
await fill(user, 'CorrectHorse12', 'CorrectHorse13')
expect(screen.getByText(fr['auth.error.password_mismatch'])).toBeInTheDocument()
})
it('sends display name + locale as metadata and shows the inbox step', async () => {
fake.auth.signUp.mockResolvedValue({ data: { session: null, user: null }, error: null })
const user = userEvent.setup()
mount()
await fill(user, 'CorrectHorse12')
expect(await screen.findByText(fr['auth.signup.check_inbox_title'])).toBeInTheDocument()
expect(screen.getByText(/alice@example\.test/)).toBeInTheDocument()
const [call] = fake.auth.signUp.mock.calls[0] as [Record<string, unknown>]
expect(call).toMatchObject({
email: 'alice@example.test',
password: 'CorrectHorse12',
options: {
data: { display_name: 'Alice', locale: 'fr' },
},
})
const options = call.options as { emailRedirectTo: string }
expect(options.emailRedirectTo).toMatch(/\/auth\/callback$/)
})
it('tells when the address is already taken', async () => {
fake.auth.signUp.mockResolvedValue({
data: { session: null, user: null },
error: { code: 'user_already_exists', message: 'User already registered', status: 422 },
})
const user = userEvent.setup()
mount()
await fill(user, 'CorrectHorse12')
expect(await screen.findByText(fr['auth.failure.user_exists'])).toBeInTheDocument()
})
})
@@ -0,0 +1,67 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createFakeSupabase,
fakeProfile,
fakeSession,
flush,
type FakeSupabase,
} from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { startLocaleSync } from '@/services/localeSync'
let fake: FakeSupabase
let stops: Array<() => void> = []
beforeEach(() => {
localStorage.clear()
useLocaleStore.setState({ locale: 'fr' })
useAuthStore.setState({
status: 'loading',
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
urlFailure: null,
})
fake = createFakeSupabase({
profiles: [fakeProfile({ locale: 'en' })],
profile_roles: [],
})
mocks.fake = fake
stops = [useAuthStore.getState().start(), startLocaleSync()]
})
afterEach(() => stops.forEach((s) => s()))
describe('locale sync', () => {
it('applies the account locale once when the profile loads', async () => {
fake.emit('SIGNED_IN', fakeSession())
await flush()
expect(useLocaleStore.getState().locale).toBe('en')
expect(localStorage.getItem('osteo:locale')).toBe('en')
})
it('saves a language switch to profiles.locale while signed in', async () => {
fake.emit('SIGNED_IN', fakeSession())
await flush()
useLocaleStore.getState().setLocale('fr')
await flush()
expect(fake.tables.profiles[0].locale).toBe('fr')
expect(useAuthStore.getState().profile?.locale).toBe('fr')
})
it('leaves the profile alone when signed out', async () => {
fake.emit('INITIAL_SESSION', null)
useLocaleStore.getState().setLocale('fr')
await flush()
expect(fake.tables.profiles[0].locale).toBe('en')
})
})
@@ -0,0 +1,93 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import AppLayout from '@/components/shell/AppLayout'
import { monogram } from '@/components/shell/UserBadge'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile({ display_name: 'Alice Local' }),
roles: [],
})
})
afterEach(cleanup)
function mount(path = '/app') {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/" element={<p>local tool</p>} />
<Route path="/app" element={<AppLayout />}>
<Route index element={<p>dashboard page</p>} />
<Route path="account" element={<p>account page</p>} />
</Route>
</Routes>
</MemoryRouter>,
)
}
describe('AppLayout', () => {
it('renders the sidebar navigation, the user and the page', () => {
mount()
const nav = screen.getByRole('navigation', { name: fr['shell.nav_label'] })
expect(nav).toHaveTextContent(fr['shell.nav.dashboard'])
expect(nav).toHaveTextContent(fr['shell.nav.account'])
expect(nav).toHaveTextContent(fr['shell.nav.local_tool'])
expect(screen.getAllByText('Alice Local').length).toBeGreaterThan(0)
expect(screen.getByText('dashboard page')).toBeInTheDocument()
})
it('marks the active destination', () => {
mount('/app/account')
const link = screen.getByRole('link', { name: new RegExp(fr['shell.nav.account']) })
expect(link).toHaveAttribute('aria-current', 'page')
})
it('opens the mobile drawer from the menu button and closes it on navigation', async () => {
const user = userEvent.setup()
mount()
await user.click(screen.getByRole('button', { name: fr['shell.open_menu'] }))
const drawer = await screen.findByRole('dialog', { name: fr['shell.nav_label'] })
expect(drawer).toBeInTheDocument()
const links = screen.getAllByRole('link', { name: new RegExp(fr['shell.nav.account']) })
await user.click(links[links.length - 1])
expect(await screen.findByText('account page')).toBeInTheDocument()
})
it('signs out and returns to the local tool', async () => {
const user = userEvent.setup()
mount()
const [button] = screen.getAllByRole('button', { name: fr['shell.sign_out'] })
await user.click(button)
expect(fake.auth.signOut).toHaveBeenCalled()
expect(await screen.findByText('local tool')).toBeInTheDocument()
})
})
describe('monogram', () => {
it('takes initials, else two letters, else ?', () => {
expect(monogram('Alice Local', undefined)).toBe('AL')
expect(monogram('Alice', undefined)).toBe('AL')
expect(monogram(undefined, 'bob@x.test')).toBe('BO')
expect(monogram('', '')).toBe('?')
})
})
+107
View File
@@ -0,0 +1,107 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createFakeSupabase,
fakeSession,
flush,
type FakeSupabase,
} from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import { useAuthStore } from '@/state/authStore'
const INITIAL = {
status: 'loading' as const,
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
urlFailure: null,
}
let fake: FakeSupabase
let stop: () => void = () => undefined
beforeEach(() => {
useAuthStore.setState(INITIAL)
fake = createFakeSupabase()
fake.tables.profile_roles = [
{ user_id: 'user-1', role: 'admin', revoked_at: null },
{ user_id: 'user-1', role: 'support', revoked_at: '2026-01-01' },
]
mocks.fake = fake
})
afterEach(() => stop())
describe('authStore', () => {
it('is unavailable when no backend is configured', () => {
mocks.fake = null
stop = useAuthStore.getState().start()
expect(useAuthStore.getState().status).toBe('unavailable')
})
it('loads the profile and active roles after SIGNED_IN', async () => {
stop = useAuthStore.getState().start()
expect(fake.auth.initialize).toHaveBeenCalled()
fake.emit('SIGNED_IN', fakeSession())
expect(useAuthStore.getState().status).toBe('signed_in')
await flush()
const s = useAuthStore.getState()
expect(s.profile?.display_name).toBe('Alice Local')
expect(s.roles).toEqual(['admin'])
})
it('clears everything on SIGNED_OUT and on an INITIAL_SESSION without session', async () => {
stop = useAuthStore.getState().start()
fake.emit('INITIAL_SESSION', null)
expect(useAuthStore.getState().status).toBe('signed_out')
fake.emit('SIGNED_IN', fakeSession())
await flush()
fake.emit('SIGNED_OUT', null)
expect(useAuthStore.getState()).toMatchObject({
status: 'signed_out',
user: null,
profile: null,
roles: [],
})
})
it('flags a recovery link until the password is saved', () => {
stop = useAuthStore.getState().start()
fake.emit('PASSWORD_RECOVERY', fakeSession())
expect(useAuthStore.getState().recovery).toBe(true)
useAuthStore.getState().clearRecovery()
expect(useAuthStore.getState().recovery).toBe(false)
})
it('records a URL exchange failure for the landing routes', async () => {
fake.auth.initialize.mockResolvedValueOnce({
error: { code: 'flow_state_expired', message: 'x', status: 400 },
})
stop = useAuthStore.getState().start()
await flush()
expect(useAuthStore.getState().urlFailure).toBe('link_expired')
})
it('updateProfile writes the row and keeps the store in sync', async () => {
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await flush()
await useAuthStore.getState().updateProfile({ first_name: 'Alice' })
expect(useAuthStore.getState().profile?.first_name).toBe('Alice')
expect(fake.tables.profiles[0].first_name).toBe('Alice')
})
it('signOut calls the client and resets the state', async () => {
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await useAuthStore.getState().signOut()
expect(fake.auth.signOut).toHaveBeenCalled()
expect(useAuthStore.getState().status).toBe('signed_out')
})
})
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import type { AuthError } from '@supabase/supabase-js'
import { classifyAuthError } from '../src/auth'
function err(patch: Partial<AuthError> & { code?: string }): AuthError {
return { name: 'AuthApiError', message: 'm', ...patch } as AuthError
}
describe('classifyAuthError', () => {
it('maps GoTrue codes to the closed kinds the UI phrases', () => {
expect(classifyAuthError(err({ code: 'invalid_credentials', status: 400 }))).toBe('invalid_credentials')
expect(classifyAuthError(err({ code: 'email_not_confirmed', status: 400 }))).toBe('email_not_confirmed')
expect(classifyAuthError(err({ code: 'user_already_exists', status: 422 }))).toBe('user_exists')
expect(classifyAuthError(err({ code: 'weak_password', status: 422 }))).toBe('weak_password')
expect(classifyAuthError(err({ code: 'otp_expired', status: 403 }))).toBe('link_expired')
expect(classifyAuthError(err({ code: 'bad_code_verifier', status: 400 }))).toBe('link_expired')
})
it('falls back on the HTTP status, then network, then unknown', () => {
expect(classifyAuthError(err({ status: 429 }))).toBe('rate_limited')
expect(classifyAuthError(err({ status: 400, message: 'Invalid login credentials' }))).toBe('invalid_credentials')
expect(classifyAuthError(err({ status: 0 }))).toBe('network')
expect(classifyAuthError(err({ status: 500, code: 'unexpected_failure' }))).toBe('unknown')
})
})