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
{loc.pathname + loc.search}
}
function mount(path: string) {
return render(
} />
}>
signup form} />
}>
dashboard} />
account} />
,
)
}
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()
})
})