feat: add JWT authentication with auth pages and tests (M5)
Backend (FastAPI): - core/auth.py: PBKDF2-HMAC-SHA256 password hashing (120k iterations, random salt), HS256 JWT creation/verification (7-day expiry, HN_SECRET_KEY via config) and get_current_user Bearer dependency - models/user.py: User model (username unique/indexed, password_hash, created_at); schemas/auth.py: register/login/token/user schemas - api/v1/auth.py: POST /api/v1/auth/register (201), /login, /logout (204), GET /me; 400 on duplicate username, 401 on bad credentials, invalid/expired/unknown tokens - requirements: PyJWT; env templates + docker-compose expose HN_SECRET_KEY (dev default, override in production) - tests: 24 new backend tests (hashing, tokens, all endpoints) Frontend (React + TypeScript): - api/client.ts: AUTH_TOKEN localStorage persistence, automatic Bearer token attachment, 401 clears the stored token, typed login/register/logout/me helpers - auth.tsx: AuthProvider (session restore + login/register/logout) and RequireAuth route guard - pages: Login, Register, SignOut and a protected /account placeholder; header shows sign-in/register or user/sign-out - styles: auth component classes in globals.css - tests: unit tests for the client, provider and pages; Playwright E2E spec covering register/login/logout, session restore, invalid token cleanup and protected-route redirects (API mocked) Note: the milestone's /api/auth/* paths map to the project's established /api/v1/* prefix (see M2); the HN_SECRET_KEY default is newzy-dev-secret-change-me.
This commit is contained in:
1 parent
ed7b30438e
commit
b186d0f797
35 files changed
+2422
-36
No files matched your search
@@ -1,18 +1,33 @@
|
||||
import { fireEvent, screen, within } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { me } from '../api/client';
|
||||
import Header from '../components/ui/Header';
|
||||
import { renderWithRouter } from './utils';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Header', () => {
|
||||
afterEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the brand with the logo', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
const brand = screen.getByRole('link', { name: 'newzy' });
|
||||
expect(brand).toHaveAttribute('href', '/');
|
||||
expect(brand.querySelector('img')).toHaveAttribute('src', expect.stringContaining('logo'));
|
||||
});
|
||||
|
||||
it('renders the primary navigation with router links and lucide icons', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||
expect(within(nav).getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
|
||||
@@ -24,7 +39,7 @@ describe('Header', () => {
|
||||
});
|
||||
|
||||
it('marks the active route in the navigation', () => {
|
||||
renderWithRouter(<Header />, { route: '/categories' });
|
||||
renderWithAuth(<Header />, { route: '/categories' });
|
||||
|
||||
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
|
||||
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveClass('bg-blue-50');
|
||||
@@ -32,7 +47,7 @@ describe('Header', () => {
|
||||
});
|
||||
|
||||
it('toggles the mobile menu', () => {
|
||||
renderWithRouter(<Header />);
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
// Mobile menu is closed by default.
|
||||
expect(screen.queryByRole('navigation', { name: 'Mobile navigation' })).not.toBeInTheDocument();
|
||||
@@ -50,6 +65,35 @@ describe('Header', () => {
|
||||
screen.queryByRole('navigation', { name: 'Mobile navigation' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows sign-in and register links when signed out', async () => {
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const accountNav = screen.getByRole('navigation', { name: 'Account' });
|
||||
expect(await within(accountNav).findByRole('link', { name: 'Sign in' })).toHaveAttribute(
|
||||
'href',
|
||||
'/login',
|
||||
);
|
||||
expect(within(accountNav).getByRole('link', { name: /register/i })).toHaveAttribute(
|
||||
'href',
|
||||
'/register',
|
||||
);
|
||||
expect(within(accountNav).queryByRole('link', { name: /sign out/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the username and sign-out link when signed in', async () => {
|
||||
(me as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem('AUTH_TOKEN', 'stored-token');
|
||||
|
||||
renderWithAuth(<Header />);
|
||||
|
||||
const accountNav = screen.getByRole('navigation', { name: 'Account' });
|
||||
expect(await within(accountNav).findByText('alice')).toBeInTheDocument();
|
||||
expect(within(accountNav).getByRole('link', { name: 'Sign out' })).toHaveAttribute(
|
||||
'href',
|
||||
'/sign-out',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const NAV_ITEM_COUNT = 3;
|
||||
@@ -3,10 +3,15 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { getHealth } from '../api/client';
|
||||
import Layout from '../components/ui/Layout';
|
||||
import { renderWithRouter } from './utils';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
getHealth: vi.fn(),
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('Layout', () => {
|
||||
@@ -17,7 +22,7 @@ describe('Layout', () => {
|
||||
it('renders the header, main content area and footer', () => {
|
||||
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>Page content</p>
|
||||
</Layout>,
|
||||
@@ -33,7 +38,7 @@ describe('Layout', () => {
|
||||
it('shows the API as online when the health check succeeds', async () => {
|
||||
(getHealth as Mock).mockResolvedValue({ status: 'ok', version: '0.1.0' });
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>content</p>
|
||||
</Layout>,
|
||||
@@ -46,7 +51,7 @@ describe('Layout', () => {
|
||||
it('shows the API as offline when the health check fails', async () => {
|
||||
(getHealth as Mock).mockRejectedValue(new Error('offline'));
|
||||
|
||||
renderWithRouter(
|
||||
renderWithAuth(
|
||||
<Layout>
|
||||
<p>content</p>
|
||||
</Layout>,
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import {
|
||||
TOKEN_KEY,
|
||||
login as clientLogin,
|
||||
logout as clientLogout,
|
||||
me as clientMe,
|
||||
register as clientRegister,
|
||||
} from '../api/client';
|
||||
import { AuthProvider, RequireAuth, useAuth } from '../auth';
|
||||
import { renderWithAuth } from './utils';
|
||||
|
||||
vi.mock('../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
/** Renders the current auth state plus one trigger button per action. */
|
||||
function StateProbe() {
|
||||
const { username, ready, login, register, logout } = useAuth();
|
||||
return (
|
||||
<div>
|
||||
<span data-testid="ready">{String(ready)}</span>
|
||||
<span data-testid="username">{username ?? 'null'}</span>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="do-login"
|
||||
onClick={() => {
|
||||
void login('login-user', 'password123');
|
||||
}}
|
||||
>
|
||||
login
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="do-register"
|
||||
onClick={() => {
|
||||
void register('register-user', 'password123');
|
||||
}}
|
||||
>
|
||||
register
|
||||
</button>
|
||||
<button type="button" data-testid="do-logout" onClick={logout}>
|
||||
logout
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
describe('AuthProvider', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('starts signed out without a stored token (no me() call)', async () => {
|
||||
renderWithAuth(<StateProbe />);
|
||||
expect(await screen.findByTestId('ready')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('null');
|
||||
expect(clientMe).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('restores the session from a valid stored token', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
|
||||
expect(await screen.findByTestId('username')).toHaveTextContent('alice');
|
||||
expect(clientMe).toHaveBeenCalledWith('valid-token');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('valid-token');
|
||||
});
|
||||
|
||||
it('clears an invalid stored token on restore failure', async () => {
|
||||
(clientMe as Mock).mockRejectedValue(new Error('401'));
|
||||
localStorage.setItem(TOKEN_KEY, 'expired-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
|
||||
expect(await screen.findByTestId('ready')).toHaveTextContent('true');
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('null');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('login stores the returned token and sets the username', async () => {
|
||||
(clientLogin as Mock).mockResolvedValue({ token: 'new-token', username: 'login-user' });
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await screen.findByTestId('ready');
|
||||
screen.getByTestId('do-login').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('login-user'));
|
||||
expect(clientLogin).toHaveBeenCalledWith('login-user', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('new-token');
|
||||
});
|
||||
|
||||
it('register stores the returned token and sets the username', async () => {
|
||||
(clientRegister as Mock).mockResolvedValue({
|
||||
token: 'new-token',
|
||||
username: 'register-user',
|
||||
});
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await screen.findByTestId('ready');
|
||||
screen.getByTestId('do-register').click();
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.getByTestId('username')).toHaveTextContent('register-user'),
|
||||
);
|
||||
expect(clientRegister).toHaveBeenCalledWith('register-user', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('new-token');
|
||||
});
|
||||
|
||||
it('logout calls the API best-effort and clears the session', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
(clientLogout as Mock).mockResolvedValue(undefined);
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('alice'));
|
||||
screen.getByTestId('do-logout').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('null'));
|
||||
expect(clientLogout).toHaveBeenCalledTimes(1);
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('logout still clears the session when the API call fails', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
(clientLogout as Mock).mockRejectedValue(new Error('network down'));
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderWithAuth(<StateProbe />);
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('alice'));
|
||||
screen.getByTestId('do-logout').click();
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId('username')).toHaveTextContent('null'));
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('RequireAuth', () => {
|
||||
const routes = (
|
||||
<Routes>
|
||||
<Route path="/login" element={<div>Login page</div>} />
|
||||
<Route
|
||||
path="/account"
|
||||
element={
|
||||
<RequireAuth>
|
||||
<div>Account page</div>
|
||||
</RequireAuth>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
);
|
||||
|
||||
const renderProtected = (initialPath: string) =>
|
||||
render(
|
||||
<MemoryRouter
|
||||
initialEntries={[initialPath]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>{routes}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('redirects unauthenticated users to /login', async () => {
|
||||
renderProtected('/account');
|
||||
expect(await screen.findByText('Login page')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders protected content for a signed-in user', async () => {
|
||||
(clientMe as Mock).mockResolvedValue({ username: 'alice' });
|
||||
localStorage.setItem(TOKEN_KEY, 'valid-token');
|
||||
|
||||
renderProtected('/account');
|
||||
expect(await screen.findByText('Account page')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Unit tests for the auth methods of the API client (token attachment,
|
||||
* 401 handling, request/response shapes).
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { ApiError, login, logout, me, register, TOKEN_KEY } from '../api/client';
|
||||
|
||||
/** Minimal fetch Response look-alike for the client. */
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
statusText: 'OK',
|
||||
json: async () => body,
|
||||
text: async () => JSON.stringify(body),
|
||||
} as Response;
|
||||
}
|
||||
|
||||
describe('auth API client', () => {
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
});
|
||||
|
||||
it('login posts credentials to /auth/login and returns the token payload', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { token: 'tok', username: 'alice' }));
|
||||
|
||||
const res = await login('alice', 'password123');
|
||||
|
||||
expect(res).toEqual({ token: 'tok', username: 'alice' });
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/login');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
username: 'alice',
|
||||
password: 'password123',
|
||||
});
|
||||
});
|
||||
|
||||
it('register posts to /auth/register', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(201, { token: 'tok', username: 'bob' }));
|
||||
|
||||
await register('bob', 'password123');
|
||||
|
||||
const [url] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/register');
|
||||
});
|
||||
|
||||
it('attaches the stored token as a Bearer Authorization header', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'stored-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me();
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer stored-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('sends no Authorization header without a stored token', async () => {
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me();
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBeUndefined();
|
||||
});
|
||||
|
||||
it('me() prefers an explicit token over the stored one', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'stored-token');
|
||||
fetchMock.mockResolvedValue(jsonResponse(200, { username: 'alice' }));
|
||||
|
||||
await me('explicit-token');
|
||||
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect((init.headers as Record<string, string>).Authorization).toBe(
|
||||
'Bearer explicit-token',
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the stored token on a 401 response', async () => {
|
||||
localStorage.setItem(TOKEN_KEY, 'dead-token');
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(401, { detail: 'Invalid or expired token', code: 'unauthorized' }),
|
||||
);
|
||||
|
||||
await expect(me('dead-token')).rejects.toBeInstanceOf(ApiError);
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces the backend error detail for failed registrations', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
jsonResponse(400, { detail: 'Username already exists', code: 'bad_request' }),
|
||||
);
|
||||
|
||||
const err = await register('alice', 'password123').catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(ApiError);
|
||||
expect((err as ApiError).status).toBe(400);
|
||||
expect((err as ApiError).code).toBe('bad_request');
|
||||
expect((err as ApiError).message).toBe('Username already exists');
|
||||
});
|
||||
|
||||
it('logout posts to /auth/logout and resolves to undefined', async () => {
|
||||
fetchMock.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 204,
|
||||
statusText: 'No Content',
|
||||
} as Response);
|
||||
|
||||
await expect(logout()).resolves.toBeUndefined();
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toBe('/api/v1/auth/logout');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(init.body).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, login as clientLogin } from '../../api/client';
|
||||
import { AuthProvider } from '../../auth';
|
||||
import Login from '../../pages/Login';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderLogin() {
|
||||
return (
|
||||
<MemoryRouter
|
||||
initialEntries={['/login']}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/" element={<div>Home page</div>} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
async function fillLoginForm(username: string, password: string) {
|
||||
fireEvent.change(screen.getByLabelText('Username'), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
|
||||
const form = screen.getByRole('button', { name: /sign in/i }).closest('form');
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
}
|
||||
|
||||
describe('Login page', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the form fields and a link to registration', () => {
|
||||
render(renderLogin());
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();
|
||||
expect(screen.getByRole('link', { name: /register/i })).toHaveAttribute('href', '/register');
|
||||
});
|
||||
|
||||
it('blocks submission with empty fields', async () => {
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
const form = screen.getByRole('button', { name: /sign in/i }).closest('form');
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(
|
||||
'Please enter both username and password.',
|
||||
);
|
||||
expect(clientLogin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('signs in, stores the token and navigates to home', async () => {
|
||||
(clientLogin as Mock).mockResolvedValue({ token: 'tok-123', username: 'alice' });
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'password123');
|
||||
|
||||
expect(await screen.findByText('Home page')).toBeInTheDocument();
|
||||
expect(clientLogin).toHaveBeenCalledWith('alice', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('tok-123');
|
||||
});
|
||||
|
||||
it('shows the backend error on failed login and stores no token', async () => {
|
||||
(clientLogin as Mock).mockRejectedValue(
|
||||
new Error('Invalid username or password'),
|
||||
);
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'wrong-password');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Invalid username or password');
|
||||
expect(screen.getByRole('button', { name: /sign in/i })).toBeEnabled();
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a loading state while the login request is pending', async () => {
|
||||
(clientLogin as Mock).mockReturnValue(new Promise(() => undefined));
|
||||
render(renderLogin());
|
||||
await screen.findByTestId('login-card');
|
||||
|
||||
await fillLoginForm('alice', 'password123');
|
||||
|
||||
expect(await screen.findByText('Signing in…')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /signing in/i })).toBeDisabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { MemoryRouter, Route, Routes } from 'react-router-dom';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Mock } from 'vitest';
|
||||
import { TOKEN_KEY, register as clientRegister } from '../../api/client';
|
||||
import { AuthProvider } from '../../auth';
|
||||
import Register from '../../pages/Register';
|
||||
|
||||
vi.mock('../../api/client', () => ({
|
||||
TOKEN_KEY: 'AUTH_TOKEN',
|
||||
login: vi.fn(),
|
||||
register: vi.fn(),
|
||||
me: vi.fn(),
|
||||
logout: vi.fn(),
|
||||
}));
|
||||
|
||||
function renderRegister() {
|
||||
return (
|
||||
<MemoryRouter
|
||||
initialEntries={['/register']}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<div>Home page</div>} />
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
async function fillRegisterForm(
|
||||
username: string,
|
||||
password: string,
|
||||
confirm: string,
|
||||
): Promise<void> {
|
||||
fireEvent.change(screen.getByLabelText('Username'), { target: { value: username } });
|
||||
fireEvent.change(screen.getByLabelText('Password'), { target: { value: password } });
|
||||
fireEvent.change(screen.getByLabelText('Confirm password'), {
|
||||
target: { value: confirm },
|
||||
});
|
||||
const form = screen.getByRole('button', { name: /register/i }).closest('form');
|
||||
expect(form).not.toBeNull();
|
||||
fireEvent.submit(form as HTMLFormElement);
|
||||
}
|
||||
|
||||
describe('Register page', () => {
|
||||
beforeEach(() => {
|
||||
localStorage.clear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders the form fields and a link to login', () => {
|
||||
render(renderRegister());
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Password')).toBeInTheDocument();
|
||||
expect(screen.getByLabelText('Confirm password')).toBeInTheDocument();
|
||||
expect(screen.getByRole('link', { name: /sign in/i })).toHaveAttribute('href', '/login');
|
||||
});
|
||||
|
||||
it('rejects mismatched passwords without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'different123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Passwords do not match.');
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects invalid usernames without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('ab', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/3–20 characters/);
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects short passwords without calling the API', async () => {
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'short', 'short');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/at least 8 characters/);
|
||||
expect(clientRegister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('registers, stores the token and navigates to home', async () => {
|
||||
(clientRegister as Mock).mockResolvedValue({ token: 'tok-456', username: 'newuser' });
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByText('Home page')).toBeInTheDocument();
|
||||
expect(clientRegister).toHaveBeenCalledWith('newuser', 'password123');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBe('tok-456');
|
||||
});
|
||||
|
||||
it('shows the backend error for an existing username', async () => {
|
||||
(clientRegister as Mock).mockRejectedValue(
|
||||
new Error('Username already exists'),
|
||||
);
|
||||
render(renderRegister());
|
||||
await screen.findByTestId('register-card');
|
||||
|
||||
await fillRegisterForm('newuser', 'password123', 'password123');
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Username already exists');
|
||||
expect(localStorage.getItem(TOKEN_KEY)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,52 @@
|
||||
/**
|
||||
* Vitest setup: registers jest-dom matchers and cleans up the DOM after
|
||||
* every test (React Testing Library auto-cleanup needs this when globals
|
||||
* are disabled).
|
||||
* Vitest setup: registers jest-dom matchers, provides a working
|
||||
* `localStorage` and cleans up the DOM after every test (React Testing
|
||||
* Library auto-cleanup needs this when globals are disabled).
|
||||
*/
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { cleanup } from '@testing-library/react';
|
||||
import { afterEach } from 'vitest';
|
||||
|
||||
/**
|
||||
* In-memory Storage. Node >= 22 exposes an experimental `localStorage`
|
||||
* global that is `undefined` without `--localstorage-file`, and the jsdom
|
||||
* environment does not override it — so the auth tests (which persist the
|
||||
* JWT under AUTH_TOKEN) get a real storage implementation here.
|
||||
*/
|
||||
class MemoryStorage implements Storage {
|
||||
private store = new Map<string, string>();
|
||||
|
||||
get length(): number {
|
||||
return this.store.size;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
getItem(key: string): string | null {
|
||||
return this.store.has(key) ? this.store.get(key)! : null;
|
||||
}
|
||||
|
||||
key(index: number): string | null {
|
||||
return Array.from(this.store.keys())[index] ?? null;
|
||||
}
|
||||
|
||||
removeItem(key: string): void {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
setItem(key: string, value: string): void {
|
||||
this.store.set(key, String(value));
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: new MemoryStorage(),
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
@@ -1,12 +1,23 @@
|
||||
import { render, type RenderOptions } from '@testing-library/react';
|
||||
import type { ReactElement } from 'react';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { AuthProvider } from '../auth';
|
||||
|
||||
export interface RenderWithRouterOptions extends Omit<RenderOptions, 'wrapper'> {
|
||||
/** Initial route (path only, e.g. "/articles/1"). */
|
||||
route?: string;
|
||||
}
|
||||
|
||||
interface RouterFutureFlags {
|
||||
v7_startTransition: boolean;
|
||||
v7_relativeSplatPath: boolean;
|
||||
}
|
||||
|
||||
const ROUTER_FUTURE: RouterFutureFlags = {
|
||||
v7_startTransition: true,
|
||||
v7_relativeSplatPath: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Render helper that wraps the UI in a MemoryRouter so components using
|
||||
* react-router-dom (Link, NavLink, useParams) can be tested in isolation.
|
||||
@@ -15,12 +26,26 @@ export function renderWithRouter(ui: ReactElement, options: RenderWithRouterOpti
|
||||
const { route = '/', ...renderOptions } = options;
|
||||
|
||||
return render(
|
||||
<MemoryRouter
|
||||
initialEntries={[route]}
|
||||
future={{ v7_startTransition: true, v7_relativeSplatPath: true }}
|
||||
>
|
||||
<MemoryRouter initialEntries={[route]} future={ROUTER_FUTURE}>
|
||||
{ui}
|
||||
</MemoryRouter>,
|
||||
renderOptions,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render helper for auth-aware components: additionally wraps the UI in
|
||||
* the app's `AuthProvider`. Tests that care about the auth API should
|
||||
* mock `../api/client`; with an empty localStorage no network calls are
|
||||
* made during session restore.
|
||||
*/
|
||||
export function renderWithAuth(ui: ReactElement, options: RenderWithRouterOptions = {}) {
|
||||
const { route = '/', ...renderOptions } = options;
|
||||
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[route]} future={ROUTER_FUTURE}>
|
||||
<AuthProvider>{ui}</AuthProvider>
|
||||
</MemoryRouter>,
|
||||
renderOptions,
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user