test(e2e): run Playwright against an isolated Compose stand
This commit is contained in:
1 parent
7a5105acc7
commit
4cd7d060bd
23 files changed
+431
-41
No files matched your search
@@ -6,3 +6,5 @@ src/shared/api/schemas/
|
||||
scripts/fixtures/
|
||||
pnpm-lock.yaml
|
||||
.orval-compat-*/
|
||||
test-results/
|
||||
playwright-report/
|
||||
@@ -11,6 +11,7 @@ A React and TypeScript SPA built with Vite and organized using FSD. The interfac
|
||||
- `src/shared/ui/` holds design tokens, fonts, logos, and primitives; `src/shared/config/` holds route paths; `src/shared/api/` holds the API client with generated endpoints, Zod schemas, and MSW mocks.
|
||||
- `codegen/orval.config.ts` configures generation from the shared OpenAPI contract.
|
||||
- `scripts/` checks FSD boundaries and Orval compatibility with the OpenAPI 3.2 fixture.
|
||||
- `e2e/` holds Playwright specs and `playwright.config.ts` configures them; they run only against a Compose stack.
|
||||
|
||||
From the repository root, `make -C frontend dev` starts development and `make -C frontend check` runs checks and builds the app. In Docker, Nginx serves the built files using configuration from `deploy/nginx/`.
|
||||
|
||||
@@ -79,4 +80,6 @@ Accessibility: every shell starts with a skip link to `main`, has landmarks and
|
||||
|
||||
Vitest runs in the Node environment with no DOM library. Routes are rendered through React Router's static handler and checked as HTML: shells, landmarks, the skip link, the active item, redirects, and not-found pages. State tests render components to markup; the query-error test runs the real `QueryClient` with the generated health operation and a stubbed `fetch`. Clicks and focus movement are checked manually in a browser; automated interaction tests need a DOM environment, which is a separate dependency decision.
|
||||
|
||||
Playwright specs in `e2e/` run in a real Chromium against the built frontend and backend: `make -C deploy test-e2e` starts a throwaway Compose stack and runs them in the official Playwright image, so no browser is installed on the host. Vitest excludes `e2e/`; `make -C frontend typecheck` and lint cover the specs. Artifacts of the last run are in `test-results/e2e/`. Details: [TESTING.md](../docs/en/TESTING.md#browser-e2e-suite).
|
||||
|
||||
See the [development guide](../docs/en/DEVELOPMENT.md).
|
||||
@@ -11,6 +11,7 @@ SPA на React и TypeScript со сборкой Vite и структурой FS
|
||||
- `src/shared/ui/` - токены дизайна, шрифты, логотипы и примитивы; `src/shared/config/` - пути маршрутов; `src/shared/api/` - API-клиент со сгенерированными endpoints, схемами Zod и MSW-моками.
|
||||
- `codegen/orval.config.ts` - генерация из общего OpenAPI-контракта.
|
||||
- `scripts/` - проверки границ FSD и совместимости Orval с фикстурой OpenAPI 3.2.
|
||||
- `e2e/` - спецификации Playwright, их настройки в `playwright.config.ts`; запускаются только на Compose-стеке.
|
||||
|
||||
Из корня: `make -C frontend dev` запускает разработку, `make -C frontend check` - проверки и сборку. В Docker собранные файлы раздает Nginx с конфигурацией из `deploy/nginx/`.
|
||||
|
||||
@@ -79,4 +80,6 @@ JetBrains Mono 2.304 (SIL OFL 1.1) раздается с нашего серве
|
||||
|
||||
Vitest работает в окружении Node без DOM-библиотеки. Маршруты отрисовываются через статический обработчик React Router и проверяются как HTML: оболочки, ориентиры, ссылка пропуска, активный пункт, перенаправления и страницы "не найдено". Тесты состояний отрисовывают компоненты в разметку; тест ошибки запроса запускает настоящий `QueryClient` со сгенерированной операцией health и подмененным `fetch`. Нажатия и перемещение фокуса проверяются вручную в браузере; автоматические тесты взаимодействия требуют DOM-окружения, а это отдельное решение о зависимости.
|
||||
|
||||
Спецификации Playwright из `e2e/` выполняются в настоящем Chromium на собранных frontend и backend: `make -C deploy test-e2e` поднимает одноразовый Compose-стек и запускает их в официальном образе Playwright, поэтому браузер на хост не ставится. Vitest исключает `e2e/`; `make -C frontend typecheck` и lint проверяют спецификации. Артефакты последнего прогона лежат в `test-results/e2e/`. Подробнее: [TESTING.md](../docs/ru/TESTING.md#браузерный-e2e-набор).
|
||||
|
||||
Подробнее: [разработка](../docs/ru/DEVELOPMENT.md).
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
// The Playwright config reads its settings from the environment. The project
|
||||
// does not depend on @types/node, so declare only the access the config uses.
|
||||
declare const process: { readonly env: Readonly<Record<string, string | undefined>> };
|
||||
@@ -0,0 +1,48 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
// Technical smoke of the real stand: the built SPA behind Nginx, the Go API
|
||||
// behind the /api proxy, and the error routes of both. It needs no data and
|
||||
// checks no candidate or employer workflow.
|
||||
|
||||
test("start page renders the SPA in Russian", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
|
||||
await expect(page.locator("html")).toHaveAttribute("lang", "ru");
|
||||
await expect(
|
||||
page.getByRole("heading", { level: 1, name: "Протокол подтвержденных навыков" }),
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("status page shows a live API", async ({ page }) => {
|
||||
const healthz = page.waitForResponse(
|
||||
(response) => new URL(response.url()).pathname === "/api/v1/healthz",
|
||||
);
|
||||
await page.goto("/status");
|
||||
|
||||
await expect(page.getByRole("heading", { level: 1, name: "Технический статус" })).toBeVisible();
|
||||
expect((await healthz).status()).toBe(200);
|
||||
await expect(page.locator("dt", { hasText: "Статус" }).locator("+ dd")).toHaveText("ok");
|
||||
});
|
||||
|
||||
test("API healthz answers through the frontend proxy", async ({ request }) => {
|
||||
const response = await request.get("/api/v1/healthz");
|
||||
|
||||
expect(response.status()).toBe(200);
|
||||
expect(await response.json()).toEqual({ status: "ok" });
|
||||
});
|
||||
|
||||
test("unknown SPA route shows the not-found page", async ({ page }) => {
|
||||
await page.goto("/e2e-missing-page");
|
||||
|
||||
await expect(page.getByRole("heading", { level: 1, name: "Страница не найдена" })).toBeVisible();
|
||||
await expect(page.getByText("/e2e-missing-page")).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "На главную" })).toHaveAttribute("href", "/");
|
||||
});
|
||||
|
||||
test("unknown API route returns a not_found problem", async ({ request }) => {
|
||||
const response = await request.get("/api/v1/missing");
|
||||
|
||||
expect(response.status()).toBe(404);
|
||||
expect(response.headers()["content-type"]).toMatch(/^application\/problem\+json\b/);
|
||||
expect(await response.json()).toMatchObject({ status: 404, code: "not_found" });
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"types": []
|
||||
},
|
||||
"include": ["./**/*.ts", "../playwright.config.ts"]
|
||||
}
|
||||
@@ -12,9 +12,9 @@
|
||||
"fmt": "prettier --write .",
|
||||
"fmt:check": "prettier --check .",
|
||||
"lint": "pnpm run lint:eslint && pnpm run lint:css",
|
||||
"lint:eslint": "eslint src codegen scripts/*.mjs *.mjs --max-warnings=0",
|
||||
"lint:eslint": "eslint src codegen e2e scripts/*.mjs *.mjs playwright.config.ts --max-warnings=0",
|
||||
"lint:css": "stylelint 'src/**/*.css' --max-warnings=0",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck": "tsc --noEmit && tsc --noEmit -p e2e/tsconfig.json",
|
||||
"test": "vitest run",
|
||||
"test:fsd": "node ./scripts/test-fsd-boundaries.mjs",
|
||||
"check": "pnpm run fmt:check && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run test:fsd && pnpm run build",
|
||||
@@ -31,6 +31,7 @@
|
||||
"devDependencies": {
|
||||
"@eslint/js": "10.0.1",
|
||||
"@faker-js/faker": "10.6.0",
|
||||
"@playwright/test": "1.63.0",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"@typescript/native": "npm:typescript@7.0.2",
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
// deploy/scripts/e2e.sh starts an isolated Compose stand and runs this suite
|
||||
// in the Playwright image that shares the frontend container's network
|
||||
// namespace, so the browser reaches the stand at http://localhost:8080.
|
||||
const baseURL = process.env.E2E_BASE_URL;
|
||||
if (!baseURL) {
|
||||
throw new Error("Set E2E_BASE_URL or run the suite with `make -C deploy test-e2e`.");
|
||||
}
|
||||
|
||||
// The suite creates synthetic data as it grows. Refuse any origin other than
|
||||
// a local stand so a misconfigured run cannot reach a shared environment.
|
||||
const allowedHosts = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
||||
if (!allowedHosts.has(new URL(baseURL).hostname)) {
|
||||
throw new Error(`E2E_BASE_URL must point to a local stand, got ${baseURL}.`);
|
||||
}
|
||||
|
||||
const artifactsDir = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "./e2e",
|
||||
outputDir: `${artifactsDir}/results`,
|
||||
forbidOnly: Boolean(process.env.CI),
|
||||
retries: 0,
|
||||
reporter: [["list"], ["html", { outputFolder: `${artifactsDir}/report`, open: "never" }]],
|
||||
use: {
|
||||
baseURL,
|
||||
locale: "ru-RU",
|
||||
trace: "retain-on-failure",
|
||||
screenshot: "only-on-failure",
|
||||
video: "off",
|
||||
},
|
||||
projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
|
||||
});
|
||||
Generated
+28
@@ -188,6 +188,9 @@ importers:
|
||||
'@faker-js/faker':
|
||||
specifier: 10.6.0
|
||||
version: 10.6.0
|
||||
'@playwright/test':
|
||||
specifier: 1.63.0
|
||||
version: 1.63.0
|
||||
'@types/react':
|
||||
specifier: 19.3.0
|
||||
version: 19.3.0
|
||||
@@ -787,6 +790,11 @@ packages:
|
||||
'@oxc-project/types@0.152.0':
|
||||
resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==}
|
||||
|
||||
'@playwright/test@1.63.0':
|
||||
resolution: {integrity: sha512-oxMK4vllB9RK5NQ2l1pq1IfOf2AvnEuj/vYGDj0H2nMtmtZpKtCwt/l00GEO6xjGfpBNAvjovvYdCm50dRQkpQ==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
'@rolldown/binding-android-arm-eabi@1.2.12':
|
||||
resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==}
|
||||
engines: {node: ^20.19.0 || >=22.12.0}
|
||||
@@ -2164,6 +2172,16 @@ packages:
|
||||
resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
playwright-core@1.63.0:
|
||||
resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
playwright@1.63.0:
|
||||
resolution: {integrity: sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
postcss-safe-parser@7.1.0:
|
||||
resolution: {integrity: sha512-1WzZxRLaAFwEh6Do+zyGpjWV3nGJNxxhuh7Ubu/q1ICImMgZJnLwhoaEpRbG4pJppp2Y1ncL9ffA2f+LhrefQg==}
|
||||
engines: {node: '>=18.0'}
|
||||
@@ -3138,6 +3156,10 @@ snapshots:
|
||||
|
||||
'@oxc-project/types@0.152.0': {}
|
||||
|
||||
'@playwright/test@1.63.0':
|
||||
dependencies:
|
||||
playwright: 1.63.0
|
||||
|
||||
'@rolldown/binding-android-arm-eabi@1.2.12':
|
||||
optional: true
|
||||
|
||||
@@ -4346,6 +4368,12 @@ snapshots:
|
||||
|
||||
picomatch@4.0.7: {}
|
||||
|
||||
playwright-core@1.63.0: {}
|
||||
|
||||
playwright@1.63.0:
|
||||
dependencies:
|
||||
playwright-core: 1.63.0
|
||||
|
||||
postcss-safe-parser@7.1.0(postcss@8.5.28):
|
||||
dependencies:
|
||||
postcss: 8.5.28
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vitest/config";
|
||||
import { configDefaults, defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
@@ -13,6 +13,8 @@ export default defineConfig({
|
||||
},
|
||||
test: {
|
||||
environment: "node",
|
||||
// Playwright specs run against the Compose stand, not in Vitest.
|
||||
exclude: [...configDefaults.exclude, "e2e/**"],
|
||||
restoreMocks: true,
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user