import { expect, test, type Page } from '@playwright/test'; const TOKEN = 'mock-jwt-token'; const envelope = (detail: string, code: string) => JSON.stringify({ detail, code }); /** * Mock the auth API so the flows do not depend on a running backend * (same approach as api.spec.ts). The "server" accepts: * - register: any username except `taken`, any password * - login: alice / password123 * - me: the mock token -> user `alice` */ function mockAuthApi(page: Page): void { page.route('**/api/v1/auth/register', (route) => { const body = route.request().postDataJSON(); if (body.username === 'taken') { return route.fulfill({ status: 400, contentType: 'application/json', body: envelope('Username already exists', 'bad_request'), }); } return route.fulfill({ status: 201, contentType: 'application/json', body: JSON.stringify({ token: TOKEN, username: body.username }), }); }); page.route('**/api/v1/auth/login', (route) => { const body = route.request().postDataJSON(); if (body.username !== 'alice' || body.password !== 'password123') { return route.fulfill({ status: 401, contentType: 'application/json', body: envelope('Invalid username or password', 'unauthorized'), }); } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ token: TOKEN, username: body.username }), }); }); page.route('**/api/v1/auth/me', (route) => { const header = route.request().headers()['authorization']; if (header !== `Bearer ${TOKEN}`) { return route.fulfill({ status: 401, contentType: 'application/json', body: envelope('Invalid or expired token', 'unauthorized'), }); } return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ username: 'alice' }), }); }); page.route('**/api/v1/auth/logout', (route) => route.fulfill({ status: 204 })); } /** Store a session token before the app boots (session-restore tests). */ async function seedToken(page: Page, token: string): Promise { await page.addInitScript((value) => localStorage.setItem('AUTH_TOKEN', value), token); } const readToken = (page: Page) => page.evaluate(() => localStorage.getItem('AUTH_TOKEN')); const accountNav = (page: Page) => page.getByRole('navigation', { name: 'Account' }); test.describe('auth flows', () => { test('register: creates an account, stores the token and signs the user in', async ({ page, }) => { mockAuthApi(page); await page.goto('/register'); await page.getByLabel('Username').fill('newuser'); await page.getByLabel('Password', { exact: true }).fill('password123'); await page.getByLabel('Confirm password').fill('password123'); await page.getByRole('button', { name: /register/i }).click(); // Registration auto-signs in and redirects to home. await expect(page).toHaveURL('/'); expect(await readToken(page)).toBe(TOKEN); await expect(accountNav(page).getByText('newuser')).toBeVisible(); await expect(accountNav(page).getByRole('link', { name: /sign out/i })).toBeVisible(); }); test('register: rejects a duplicate username with the backend error', async ({ page }) => { mockAuthApi(page); await page.goto('/register'); await page.getByLabel('Username').fill('taken'); await page.getByLabel('Password', { exact: true }).fill('password123'); await page.getByLabel('Confirm password').fill('password123'); await page.getByRole('button', { name: /register/i }).click(); await expect(page.getByRole('alert')).toContainText('Username already exists'); expect(await readToken(page)).toBeNull(); await expect(page).toHaveURL('/register'); }); test('register: validates mismatched passwords client-side', async ({ page }) => { mockAuthApi(page); await page.goto('/register'); await page.getByLabel('Username').fill('newuser'); await page.getByLabel('Password', { exact: true }).fill('password123'); await page.getByLabel('Confirm password').fill('different123'); await page.getByRole('button', { name: /register/i }).click(); await expect(page.getByRole('alert')).toContainText('Passwords do not match.'); expect(await readToken(page)).toBeNull(); }); test('login: stores the token and signs the user in', async ({ page }) => { mockAuthApi(page); await page.goto('/login'); await page.getByLabel('Username').fill('alice'); await page.getByLabel('Password').fill('password123'); await page.getByRole('button', { name: /sign in/i }).click(); await expect(page).toHaveURL('/'); expect(await readToken(page)).toBe(TOKEN); await expect(accountNav(page).getByText('alice')).toBeVisible(); }); test('login: shows the backend error for invalid credentials', async ({ page }) => { mockAuthApi(page); await page.goto('/login'); await page.getByLabel('Username').fill('alice'); await page.getByLabel('Password').fill('wrong-password'); await page.getByRole('button', { name: /sign in/i }).click(); await expect(page.getByRole('alert')).toContainText('Invalid username or password'); expect(await readToken(page)).toBeNull(); await expect(page).toHaveURL('/login'); }); test('restores the session from a stored token on page load', async ({ page }) => { mockAuthApi(page); await seedToken(page, TOKEN); await page.goto('/'); await expect(accountNav(page).getByText('alice')).toBeVisible(); expect(await readToken(page)).toBe(TOKEN); }); test('clears an invalid stored token on page load', async ({ page }) => { mockAuthApi(page); await seedToken(page, 'expired-or-forged-token'); await page.goto('/'); // Restore failed -> signed-out header, token removed. await expect(accountNav(page).getByRole('link', { name: 'Sign in' })).toBeVisible(); expect(await readToken(page)).toBeNull(); }); test('redirects unauthenticated users from /account to /login', async ({ page }) => { mockAuthApi(page); await page.goto('/account'); await expect(page).toHaveURL('/login'); }); test('renders the protected /account page for a signed-in user', async ({ page }) => { mockAuthApi(page); await seedToken(page, TOKEN); await page.goto('/account'); await expect(page.getByTestId('account-page')).toBeVisible(); await expect(page.getByRole('heading', { level: 1, name: 'Account' })).toBeVisible(); await expect(page.getByTestId('account-page').getByText('alice')).toBeVisible(); }); test('sign out clears the token and returns to the login page', async ({ page }) => { mockAuthApi(page); await seedToken(page, TOKEN); await page.goto('/'); await accountNav(page).getByRole('link', { name: /sign out/i }).click(); await expect(page).toHaveURL('/login'); expect(await readToken(page)).toBeNull(); await expect(page.getByRole('status').getByText(/signed out/i)).toBeVisible(); }); });