feat: add React + TypeScript frontend with Vite, routing, tests and Docker setup

M3 frontend infrastructure for the newzy news application:

- Vite + React 18 + TypeScript project (Node >=18) in frontend/
- React Router v6: BrowserRouter in App.tsx, routes for /, /articles,
  /articles/:id and /categories, Link/NavLink-based navigation
- lucide-react icons (Home, FileText, Settings, Search, ...) in the
  responsive Header (desktop + mobile menu) and article components
- Reusable components: ArticleCard, AuthorAvatar, CategoryBadge (CVA),
  Layout shell with backend API status indicator in the footer
- Typed API client (fetch wrapper, ApiError, endpoint helpers) with
  types matching the backend models; sample-data fallback until the
  backend article endpoints exist
- Tailwind CSS global/component styles, cn() helper (clsx + tailwind-merge)
- Unit tests: Vitest + React Testing Library (23 tests, 100% statement
  coverage on components)
- E2E tests: Playwright (9 tests) covering page shell, feed rendering,
  client-side navigation, article route and API interactions
- ESLint (react + react-hooks + typescript) configured and passing
- Multi-stage Dockerfile (Vite build -> Nginx) with SPA fallback and an
  /api/ proxy to the backend service; docker-compose frontend service on
  port 3000 in both frontend/ and the root docker-compose.yml
- README with setup, API documentation, testing and Docker instructions
This commit is contained in:
Daniel Samson committed 2026-10-30 14:10:29 +00:00
1 parent cbeac5e16b
commit ffe19272b3
45 files changed
+9843 -4

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
import { expect, test, type Page } from '@playwright/test';
const HEALTH_OK = { status: 'ok', version: '0.1.0' };
const API_ARTICLE = {
id: 100,
title: 'Live API Article',
content: 'This story was served by the (mocked) newzy backend API. '.repeat(20),
author_id: 7,
category_id: 1,
created_at: '2025-06-01T08:00:00Z',
published: true,
author: {
id: 7,
name: 'Ada Lovelace',
email: 'ada@example.com',
bio: null,
},
category: { id: 1, name: 'Technology', slug: 'technology' },
};
/** Mock the health endpoint so tests do not depend on a running backend. */
async function mockHealth(page: Page): Promise<void> {
await page.route('**/api/v1/health', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(HEALTH_OK),
}),
);
}
/**
* API interactions: verifies the app talks to the backend through the
* typed client (base URL /api/v1, JSON accept header) and reflects the
* responses in the UI.
*/
test.describe('api interactions', () => {
test('requests the backend health endpoint on load and reports it online', async ({
page,
}) => {
await mockHealth(page);
const healthRequest = page.waitForRequest(
(request) => request.url().includes('/api/v1/health') && request.method() === 'GET',
);
await page.goto('/');
const request = await healthRequest;
expect(request.headers()['accept']).toBe('application/json');
await expect(page.getByTestId('api-status')).toHaveText(/api:\s*online/i);
});
test('renders articles returned by the API', async ({ page }) => {
await mockHealth(page);
await page.route('**/api/v1/articles', (route) =>
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([API_ARTICLE]),
}),
);
await page.goto('/');
// The API article replaces the sample feed.
const cards = page.getByTestId('article-card');
await expect(cards).toHaveCount(1);
await expect(cards.first()).toContainText('Live API Article');
await expect(cards.first()).toContainText('Ada Lovelace');
await expect(cards.first()).toContainText('Technology');
// Sample-data fallback note is hidden when real data is present.
await expect(page.getByTestId('sample-data-note')).toHaveCount(0);
});
test('falls back to sample data and reports the API as offline', async ({ page }) => {
// Block every API call to simulate the backend being down.
await page.route('**/api/v1/**', (route) => route.abort());
await page.goto('/');
await expect(page.getByTestId('sample-data-note')).toBeVisible();
await expect(page.getByTestId('article-card').first()).toBeVisible();
await expect(page.getByTestId('api-status')).toHaveText(/api:\s*offline/i);
});
test('survives API error responses (non-2xx envelope)', async ({ page }) => {
await mockHealth(page);
await page.route('**/api/v1/articles', (route) =>
route.fulfill({
status: 404,
contentType: 'application/json',
body: JSON.stringify({ detail: 'Not Found', code: 'not_found' }),
}),
);
const pageErrors: string[] = [];
page.on('pageerror', (error) => pageErrors.push(error.message));
await page.goto('/');
// 404 from the articles endpoint -> graceful sample-data fallback.
await expect(page.getByTestId('sample-data-note')).toBeVisible();
await expect(page.getByTestId('article-card').first()).toBeVisible();
expect(pageErrors).toEqual([]);
});
});
+114
View File
@@ -0,0 +1,114 @@
import { expect, test } from '@playwright/test';
/**
* Homepage flows: page shell, article feed, and client-side navigation
* between pages via React Router links (no full page reloads).
*/
test.describe('home page', () => {
test('renders the page shell, branding and navigation', async ({ page }) => {
await page.goto('/');
await expect(page).toHaveTitle(/newzy/i);
// Layout structure: header, main content, footer.
await expect(page.getByRole('banner')).toBeVisible();
await expect(page.getByRole('main')).toBeVisible();
await expect(page.getByRole('contentinfo')).toBeVisible();
// Brand links to home.
await expect(page.getByRole('link', { name: 'newzy' })).toHaveAttribute('href', '/');
// Primary navigation uses React Router links.
const nav = page.getByRole('navigation', { name: 'Main navigation' });
await expect(nav.getByRole('link', { name: /home/i })).toHaveAttribute('href', '/');
await expect(nav.getByRole('link', { name: /articles/i })).toHaveAttribute(
'href',
'/articles',
);
await expect(nav.getByRole('link', { name: /categories/i })).toHaveAttribute(
'href',
'/categories',
);
});
test('renders the featured article and article grid with data', async ({ page }) => {
await page.goto('/');
// Hero with the featured article.
const featured = page.getByRole('region', { name: 'Featured article' });
await expect(featured).toBeVisible();
await expect(featured.getByRole('heading', { level: 1 })).toContainText(
'Inside the new wave of open-source language models',
);
// Article grid rendered from data (sample feed while the backend article
// endpoints are not available yet).
const cards = page.getByTestId('article-card');
await expect(cards.first()).toBeVisible();
expect(await cards.count()).toBeGreaterThanOrEqual(5);
await expect(page.getByTestId('sample-data-note')).toBeVisible();
});
test('navigates between pages via router links without a full page reload', async ({
page,
}) => {
const loadEvents: string[] = [];
page.on('load', () => loadEvents.push(page.url()));
await page.goto('/');
const nav = page.getByRole('navigation', { name: 'Main navigation' });
// Home -> Articles
await nav.getByRole('link', { name: /articles/i }).click();
await expect(page).toHaveURL(/\/articles$/);
await expect(
page.getByRole('heading', { level: 1, name: 'Articles' }),
).toBeVisible();
// Articles -> Categories
await nav.getByRole('link', { name: /categories/i }).click();
await expect(page).toHaveURL(/\/categories$/);
await expect(
page.getByRole('heading', { level: 1, name: 'Categories' }),
).toBeVisible();
// Categories -> Home
await nav.getByRole('link', { name: /home/i }).click();
await expect(page).toHaveURL(/\/$/);
// Only the initial goto fired a document load — the rest was
// client-side React Router navigation.
expect(loadEvents).toHaveLength(1);
});
test('opens an article detail placeholder from a card', async ({ page }) => {
await page.goto('/');
const firstCard = page.getByTestId('article-card').first();
await firstCard.getByRole('link').first().click();
await expect(page).toHaveURL(/\/articles\/\d+$/);
await expect(page.getByRole('heading', { level: 1 })).toContainText('Article #');
});
test('has no unexpected console errors or uncaught page errors', async ({ page }) => {
const consoleErrors: string[] = [];
const pageErrors: string[] = [];
page.on('console', (message) => {
if (message.type() === 'error') consoleErrors.push(message.text());
});
page.on('pageerror', (error) => pageErrors.push(error.message));
await page.goto('/');
await expect(page.getByTestId('article-card').first()).toBeVisible();
// Uncaught exceptions are never acceptable.
expect(pageErrors).toEqual([]);
// Expected noise: the article feed fetch 404s/502s when the backend
// article endpoints are unavailable (the UI falls back to sample data).
const unexpected = consoleErrors.filter(
(text) => !/failed to load resource|net::err/i.test(text),
);
expect(unexpected).toEqual([]);
});
});