196 lines
6.3 KiB
TypeScript
196 lines
6.3 KiB
TypeScript
/**
|
|||
|
|
* Tests for LoginPage (M2-T07).
|
||
|
|
*
|
||
|
|
* Strategy: vi.mock the apiClient module so we can control POST /api/auth/login
|
||
|
|
* responses without a real server. We also mock useSession so tests can control
|
||
|
|
* the authentication state.
|
||
|
|
*
|
||
|
|
* Coverage:
|
||
|
|
* 1. Renders the login form.
|
||
|
|
* 2. Successful login → invalidates session query + navigates.
|
||
|
|
* 3. 401 bad credentials → shows inline error, does not navigate.
|
||
|
|
* 4. Already-authenticated users visiting /login → redirected to '/'.
|
||
|
|
* 5. Unexpected error → shows generic error message.
|
||
|
|
*/
|
||
|
|
|
||
|
|
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||
|
|
import { screen, waitFor, fireEvent } from '@testing-library/react'
|
||
|
|
import { renderWithProviders } from '../test-utils'
|
||
|
|
import { LoginPage } from './LoginPage'
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
// Mock apiClient
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
|
||
|
|
// We mock the entire api/client module. Each test can override POST as needed.
|
||
|
|
const mockPost = vi.fn()
|
||
|
|
|
||
|
|
vi.mock('../api/client', () => ({
|
||
|
|
default: {
|
||
|
|
POST: (...args: unknown[]) => mockPost(...args),
|
||
|
|
GET: vi.fn(),
|
||
|
|
},
|
||
|
|
ApiError: class ApiError extends Error {
|
||
|
|
status: number
|
||
|
|
body: unknown
|
||
|
|
constructor(status: number, body: unknown) {
|
||
|
|
super(`API error ${status}`)
|
||
|
|
this.name = 'ApiError'
|
||
|
|
this.status = status
|
||
|
|
this.body = body
|
||
|
|
}
|
||
|
|
},
|
||
|
|
registerLoginRedirect: vi.fn(),
|
||
|
|
}))
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
// Mock useSession — default: unauthenticated
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
|
||
|
|
// Typed as returning the wider union so mockReturnValue accepts all status variants.
|
||
|
|
const mockUseSession = vi.fn(() => ({
|
||
|
|
status: 'unauthenticated' as 'loading' | 'authenticated' | 'unauthenticated',
|
||
|
|
user: null as null | { username: string; force_password_change: boolean },
|
||
|
|
}))
|
||
|
|
|
||
|
|
vi.mock('../auth/SessionProvider', () => ({
|
||
|
|
useSession: () => mockUseSession(),
|
||
|
|
SessionProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||
|
|
}))
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
// Helpers
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
|
||
|
|
function renderLogin(initialPath = '/login') {
|
||
|
|
return renderWithProviders(<LoginPage />, {
|
||
|
|
initialPath,
|
||
|
|
routes: [{ path: '/', element: <div data-testid="home-page">Home</div> }],
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
function fillAndSubmit(username: string, password: string) {
|
||
|
|
fireEvent.change(screen.getByTestId('username-input'), { target: { value: username } })
|
||
|
|
fireEvent.change(screen.getByTestId('password-input'), { target: { value: password } })
|
||
|
|
fireEvent.submit(screen.getByTestId('login-form'))
|
||
|
|
}
|
||
|
|
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
// Tests
|
||
|
|
// ---------------------------------------------------------------------------
|
||
|
|
|
||
|
|
describe('LoginPage', () => {
|
||
|
|
beforeEach(() => {
|
||
|
|
vi.clearAllMocks()
|
||
|
|
// Reset to unauthenticated by default
|
||
|
|
mockUseSession.mockReturnValue({ status: 'unauthenticated', user: null })
|
||
|
|
})
|
||
|
|
|
||
|
|
it('renders the login form with username and password fields', () => {
|
||
|
|
renderLogin()
|
||
|
|
expect(screen.getByTestId('login-form')).toBeInTheDocument()
|
||
|
|
expect(screen.getByTestId('username-input')).toBeInTheDocument()
|
||
|
|
expect(screen.getByTestId('password-input')).toBeInTheDocument()
|
||
|
|
expect(screen.getByTestId('login-submit')).toBeInTheDocument()
|
||
|
|
})
|
||
|
|
|
||
|
|
it('shows Sign In heading', () => {
|
||
|
|
renderLogin()
|
||
|
|
expect(screen.getByRole('heading', { name: /sign in/i })).toBeInTheDocument()
|
||
|
|
})
|
||
|
|
|
||
|
|
it('navigates to "/" on successful login', async () => {
|
||
|
|
// Simulate a successful POST /api/auth/login response
|
||
|
|
mockPost.mockResolvedValueOnce({
|
||
|
|
data: { user: { username: 'admin', force_password_change: false }, csrf_token: 'tok123' },
|
||
|
|
response: { status: 200, ok: true },
|
||
|
|
})
|
||
|
|
|
||
|
|
renderLogin()
|
||
|
|
fillAndSubmit('admin', 'correct-password')
|
||
|
|
|
||
|
|
await waitFor(() => {
|
||
|
|
expect(screen.getByTestId('home-page')).toBeInTheDocument()
|
||
|
|
})
|
||
|
|
})
|
||
|
|
|
||
|
|
it('calls POST /api/auth/login with the correct body', async () => {
|
||
|
|
mockPost.mockResolvedValueOnce({
|
||
|
|
data: { user: { username: 'admin', force_password_change: false }, csrf_token: 'tok123' },
|
||
|
|
response: { status: 200, ok: true },
|
||
|
|
})
|
||
|
|
|
||
|
|
renderLogin()
|
||
|
|
fillAndSubmit('myuser', 'mypassword')
|
||
|
|
|
||
|
|
await waitFor(() => {
|
||
|
|
expect(mockPost).toHaveBeenCalledWith('/api/auth/login', {
|
||
|
|
body: { username: 'myuser', password: 'mypassword' },
|
||
|
|
})
|
||
|
|
})
|
||
|
|
})
|
||
|
|
|
||
|
|
it('shows inline error on 401 and does NOT navigate', async () => {
|
||
|
|
// Simulate 401: openapi-fetch returns { data: undefined, response: { status: 401 } }
|
||
|
|
mockPost.mockResolvedValueOnce({
|
||
|
|
data: undefined,
|
||
|
|
response: { status: 401, ok: false },
|
||
|
|
})
|
||
|
|
|
||
|
|
renderLogin()
|
||
|
|
fillAndSubmit('admin', 'wrong-password')
|
||
|
|
|
||
|
|
await waitFor(() => {
|
||
|
|
expect(screen.getByTestId('login-error')).toBeInTheDocument()
|
||
|
|
})
|
||
|
|
|
||
|
|
expect(screen.getByTestId('login-error')).toHaveTextContent(
|
||
|
|
/incorrect username or password/i,
|
||
|
|
)
|
||
|
|
// Should still be on the login form, not navigated away
|
||
|
|
expect(screen.getByTestId('login-form')).toBeInTheDocument()
|
||
|
|
})
|
||
|
|
|
||
|
|
it('does not include the password in the error message', async () => {
|
||
|
|
mockPost.mockResolvedValueOnce({
|
||
|
|
data: undefined,
|
||
|
|
response: { status: 401, ok: false },
|
||
|
|
})
|
||
|
|
|
||
|
|
renderLogin()
|
||
|
|
fillAndSubmit('admin', 'super-secret-password')
|
||
|
|
|
||
|
|
await waitFor(() => {
|
||
|
|
expect(screen.getByTestId('login-error')).toBeInTheDocument()
|
||
|
|
})
|
||
|
|
|
||
|
|
expect(screen.getByTestId('login-error')).not.toHaveTextContent('super-secret-password')
|
||
|
|
})
|
||
|
|
|
||
|
|
it('shows generic error on unexpected network failure', async () => {
|
||
|
|
mockPost.mockRejectedValueOnce(new Error('Network error'))
|
||
|
|
|
||
|
|
renderLogin()
|
||
|
|
fillAndSubmit('admin', 'password')
|
||
|
|
|
||
|
|
await waitFor(() => {
|
||
|
|
expect(screen.getByTestId('login-error')).toBeInTheDocument()
|
||
|
|
})
|
||
|
|
|
||
|
|
expect(screen.getByTestId('login-error')).toHaveTextContent(/login failed/i)
|
||
|
|
})
|
||
|
|
|
||
|
|
it('redirects already-authenticated users to "/"', async () => {
|
||
|
|
mockUseSession.mockReturnValue({
|
||
|
|
status: 'authenticated',
|
||
|
|
user: { username: 'admin', force_password_change: false },
|
||
|
|
})
|
||
|
|
|
||
|
|
renderLogin()
|
||
|
|
|
||
|
|
await waitFor(() => {
|
||
|
|
expect(screen.getByTestId('home-page')).toBeInTheDocument()
|
||
|
|
})
|
||
|
|
})
|
||
|
|
})
|