Files
newz-qwen-27b/frontend/src/tests/Header.test.tsx
T
Daniel Samson b186d0f797 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.
2026-10-30 17:03:00 +00:00

100 lines
3.6 KiB
TypeScript

import { fireEvent, screen, within } from '@testing-library/react';
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 { 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', () => {
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', () => {
renderWithAuth(<Header />);
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
expect(within(nav).getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
expect(within(nav).getByRole('link', { name: /articles/i })).toHaveAttribute('href', '/articles');
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveAttribute('href', '/categories');
// Lucide icons render as inline SVGs (one per nav item).
expect(nav.querySelectorAll('svg').length).toBeGreaterThanOrEqual(NAV_ITEM_COUNT);
});
it('marks the active route in the navigation', () => {
renderWithAuth(<Header />, { route: '/categories' });
const nav = screen.getByRole('navigation', { name: 'Main navigation' });
expect(within(nav).getByRole('link', { name: /categories/i })).toHaveClass('bg-blue-50');
expect(within(nav).getByRole('link', { name: /home/i })).not.toHaveClass('bg-blue-50');
});
it('toggles the mobile menu', () => {
renderWithAuth(<Header />);
// Mobile menu is closed by default.
expect(screen.queryByRole('navigation', { name: 'Mobile navigation' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Open menu' }));
const mobileNav = screen.getByRole('navigation', { name: 'Mobile navigation' });
expect(mobileNav).toBeInTheDocument();
expect(within(mobileNav).getByRole('link', { name: /articles/i })).toHaveAttribute(
'href',
'/articles',
);
fireEvent.click(screen.getByRole('button', { name: 'Close menu' }));
expect(
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;