Files
lincodex/frontend/e2e/candidate-home.spec.ts

626 lines
26 KiB
TypeScript

import { expect, test, type Page, type Route } from "@playwright/test";
type InboxMessage = {
id?: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const password = "correct horse battery staple 2026";
test.use({ trace: "off", screenshot: "off", video: "off" });
function baseUrl(): string {
const value = process.env.E2E_BASE_URL;
if (!value) throw new Error("The local end-to-end base URL is not configured.");
return value;
}
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
const overflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(overflow, `no horizontal overflow at ${width}px`).toBe(false);
}
}
// Review screenshots contain only synthetic data from the stubbed answers.
async function captureReviewScreenshots(page: Page, name: string): Promise<void> {
const directory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
for (const width of [360, 1280]) {
await page.setViewportSize({ width, height: 1400 });
await page.screenshot({
path: `${directory}/${name}-${width}.png`,
animations: "disabled",
fullPage: true,
});
}
}
async function expectKeyboardReachesLink(page: Page, name: string): Promise<void> {
const link = page.getByRole("link", { name, exact: true }).first();
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
for (let attempt = 0; attempt < 60; attempt += 1) {
await page.keyboard.press("Tab");
if (await link.evaluate((element) => element === document.activeElement)) {
const hasRing = await link.evaluate((element) => {
if (!(element instanceof HTMLElement) || !element.matches(":focus-visible")) return false;
const style = getComputedStyle(element);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(hasRing, `visible keyboard focus on "${name}"`).toBe(true);
return;
}
}
throw new Error(`Keyboard navigation did not reach the link "${name}".`);
}
// The first group runs against the real backend and needs the mail fixture to
// confirm the address. The second group answers every API call itself, so it
// checks how the screen renders each state, not how the backend behaves.
test.describe("candidate home with the real backend", () => {
test.skip(!mailFixtureEnabled, "Requires the local mail fixture target.");
async function readInbox(email: string): Promise<InboxMessage[]> {
const inboxUrl = process.env.E2E_MAILBOX_URL;
const token = process.env.E2E_MAILBOX_TOKEN;
if (!inboxUrl || !token) {
throw new Error("The local registration mailbox fixture is not configured.");
}
const url = new URL(inboxUrl);
url.searchParams.set("to", email);
const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
if (!response.ok) throw new Error("Could not read the local registration mailbox.");
return ((await response.json()) as InboxResponse).messages;
}
async function waitForVerification(email: string): Promise<InboxMessage> {
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
const message = (await readInbox(email)).at(-1);
if (message) return message;
await new Promise((resolve) => setTimeout(resolve, 250));
}
throw new Error("The local registration mailbox did not receive the verification message.");
}
function verificationToken(message: InboxMessage): string {
const content = `${message.text ?? ""}\n${message.html ?? ""}`;
const token = /\/verify-email#token=([A-Za-z0-9_-]{32,128})/.exec(content)?.[1];
if (!token) throw new Error("The local registration message had no verification link.");
return token;
}
async function register(page: Page): Promise<string> {
const email = `home-${crypto.randomUUID()}@example.test`;
await page.goto("/register");
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("radio", { name: /Кандидат/ }).check();
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
await page.getByRole("button", { name: "Создать аккаунт" }).click();
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
const verificationUrl = new URL("/verify-email", baseUrl());
verificationUrl.hash = `token=${verificationToken(await waitForVerification(email))}`;
await page.goto(verificationUrl.toString());
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
return email;
}
async function signIn(page: Page, email: string): Promise<void> {
await page.goto("/candidate");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponse = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions",
);
await page.getByRole("button", { name: "Войти" }).click();
expect((await loginResponse).status()).toBe(201);
}
function isApiPath(pathname: string) {
return (response: { url(): string; request(): { method(): string } }) =>
response.request().method() === "GET" && new URL(response.url()).pathname === pathname;
}
test("a new candidate moves from the empty profile to the test without linking any account", async ({
page,
}) => {
test.setTimeout(120_000);
const email = await register(page);
await signIn(page, email);
await expect(page.getByRole("heading", { name: "Первые шаги" })).toBeVisible();
// Empty profile: the home leads to the form and asks for nothing else.
await page.getByRole("link", { name: "Главная", exact: true }).click();
await expect(page.getByRole("heading", { name: "Главная", level: 1 })).toBeVisible();
await expect(page.getByRole("heading", { name: "Заполните профиль" })).toBeVisible();
await expect(page.getByText(/Сохраненный шаг аккаунта: Согласия/)).toBeVisible();
await expect(page.getByText(/Привязка ФСП ID необязательна/)).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
await expect(page.getByText("Анкета еще не сохранена")).toBeVisible();
await expectNoHorizontalOverflow(page);
await page.setViewportSize({ width: 1280, height: 900 });
await expectKeyboardReachesLink(page, "Заполнить профиль");
await page.getByRole("link", { name: "Заполнить профиль", exact: true }).first().click();
await expect(page.getByRole("heading", { name: "Профиль", level: 1 })).toBeVisible();
await page.getByLabel("Имя и фамилия").fill("Тестовый кандидат");
// The profile is a form in steps: walk to the review step, then save.
for (const heading of ["Роли", "Опыт", "Проекты", "Навыки", "Условия", "Проверка"]) {
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(
page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) }),
).toBeFocused();
}
const profileSaved = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/profile",
);
await page.getByRole("button", { name: "Сохранить профиль" }).click();
expect((await profileSaved).status()).toBe(200);
// Filled profile: the next step is the questionnaire.
await page.getByRole("link", { name: "Главная", exact: true }).click();
await expect(page.getByRole("heading", { name: "Заполните анкету" })).toBeVisible();
await page.getByRole("link", { name: "Заполнить анкету", exact: true }).first().click();
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
await page.getByLabel("Специализация", { exact: true }).selectOption("backend");
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(page.getByRole("heading", { name: /\. Уровень и опыт$/ })).toBeFocused();
await page.getByLabel("Моя оценка уровня").selectOption("middle");
await page.getByRole("checkbox", { name: "Python", exact: true }).check();
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(page.getByRole("heading", { name: /\. Формат работы$/ })).toBeFocused();
await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check();
await page.getByRole("button", { name: "Далее", exact: true }).click();
await expect(page.getByRole("heading", { name: /\. Проверка и сохранение$/ })).toBeFocused();
const questionnaireSaved = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await questionnaireSaved).status()).toBe(200);
// Saved questionnaire, no category: the test is next and the declared
// grade is shown apart from the (absent) confirmed category.
const availability = page.waitForResponse(isApiPath("/api/v1/me/assessment-availability"));
await page.getByRole("link", { name: "Главная", exact: true }).click();
await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible();
const availabilityBody = (await (await availability).json()) as {
specializations: { specialization: string; confirmed_grade: string | null }[];
};
expect(availabilityBody.specializations[0]).toMatchObject({
specialization: "backend",
confirmed_grade: null,
});
await expect(page.getByText("Заявлено: Middle")).toBeVisible();
await expect(page.getByText("Пока не подтверждена")).toBeVisible();
await expect(page.getByText(/Подтверждено тестом:/)).toHaveCount(0);
// The server advances the stored step only from the matching step, so it
// still reads "Согласия" here; the next step follows the saved data.
await expect(page.getByText(/Сохраненный шаг аккаунта: Согласия/)).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
// A refresh reads the same server state again.
const refreshed = page.waitForResponse(isApiPath("/api/v1/me/assessment-availability"));
await page.reload();
expect((await refreshed).status()).toBe(200);
await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible();
await expect(page.getByText("Заявлено: Middle")).toBeVisible();
// Returning after signing in again: the saved step opens first, and the
// home shows the same state as before.
await page.context().clearCookies();
await signIn(page, email);
await expect(page.getByRole("heading", { name: "Первые шаги" })).toBeVisible();
await page.getByRole("link", { name: "Главная", exact: true }).click();
await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible();
await expect(page.getByText("Заявлено: Middle")).toBeVisible();
});
});
const accountId = "11111111-1111-4111-8111-111111111111";
const attemptId = "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80";
type Stub = { status: number; body: unknown };
type Scenario = {
step?: string;
profileVersion?: number;
declared?: { specialization: string; grade: string };
confirmed?: string | null;
results?: unknown[];
privacy?: unknown;
/** Replaces the answer for one API path, for error and forbidden states. */
stubs?: Record<string, Stub>;
};
function problem(status: number, code: string, title: string): Stub {
return {
status,
body: { type: `urn:lincodex:problem:${code}`, title, status, code },
};
}
function realResult(outcome: "confirmed" | "not_confirmed") {
const confirmed = outcome === "confirmed";
return {
attempt_id: attemptId,
specialization: "backend",
target_grade: "junior",
root_attempt_id: null,
chain_deadline: null,
task_language: "python",
kind: "root",
mode: "demo_basic",
versions: {
policy_version: 1,
bank_version: "backend-demo.2026-10.1",
algorithm_version: "basic.1",
},
outcome,
not_determined_reason: null,
confirmed_grade: confirmed ? "junior" : null,
previous_confirmed_grade: null,
category_decision: {
status: confirmed ? "assigned" : "not_confirmed",
previous_confirmed_grade: null,
current_confirmed_grade: confirmed ? "junior" : null,
method: confirmed ? "demo_basic_pass_mark" : null,
source: confirmed ? "synthetic_demo" : null,
calibration_status: "uncalibrated",
},
strength: null,
calibration_status: "uncalibrated",
limitations: ["demo_bank"],
uncertainty: null,
basic_score: null,
practices: [],
gaps: [],
durations: { items_seconds: 600, practice_seconds: null },
next_steps: [],
decided_at: "2026-10-08T10:00:00Z",
};
}
const closedPrivacy = {
publication: {
state: "closed",
closed_reason: "never_published",
fields: [],
consent_id: null,
published_at: null,
version: 0,
},
search_status: {
value: "not_looking",
lapsed: false,
confirmed_at: null,
lapses_at: null,
version: 0,
},
hidden_organizations_total: 0,
};
function scenarioAnswer(scenario: Scenario, pathname: string): Stub {
const stub = scenario.stubs?.[pathname];
if (stub) return stub;
const declared = scenario.declared;
switch (pathname) {
case "/api/v1/identity/sessions/current":
return {
status: 200,
body: {
account: {
id: accountId,
email: "person@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: scenario.step ?? "candidate_profile",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
},
};
case "/api/v1/me/profile":
// The home reads only the version; the profile form is not opened here.
return {
status: 200,
body: { version: scenario.profileVersion ?? 0, confirmed_categories: [] },
};
case "/api/v1/me/questionnaire":
return {
status: 200,
body: {
version: declared ? 1 : 0,
specializations: declared
? [
{
specialization: declared.specialization,
self_assessed_grade: declared.grade,
task_languages: [],
stack: [],
experience: null,
},
]
: [],
work_context: null,
updated_at: declared ? "2026-10-07T12:30:00Z" : null,
},
};
case "/api/v1/me/assessment-availability":
return {
status: 200,
body: {
specializations: declared
? [
{
specialization: declared.specialization,
confirmed_grade: scenario.confirmed ?? null,
confirmed_basis: scenario.confirmed ? "synthetic_demo" : null,
active_attempt_id: null,
grades: [
{
grade: declared.grade,
status: "available",
mode: "demo_basic",
available_at: null,
time_limit_seconds: 3600,
max_sessions: 2,
max_items: 20,
practice_required: false,
},
],
},
]
: [],
},
};
case "/api/v1/me/assessment-results":
return {
status: 200,
body: {
items: scenario.results ?? [],
page: { has_more: false, next_cursor: null },
},
};
case "/api/v1/me/invitations":
return {
status: 200,
body: {
items: [],
page: { has_more: false, next_cursor: null },
},
};
case "/api/v1/me/privacy":
return { status: 200, body: scenario.privacy ?? closedPrivacy };
default:
return problem(404, "not_found", "Not found");
}
}
async function mockCandidateApi(page: Page, scenario: Scenario): Promise<void> {
await page.route("**/api/v1/**", async (route: Route) => {
const { pathname } = new URL(route.request().url());
const answer =
route.request().method() === "GET"
? scenarioAnswer(scenario, pathname)
: problem(405, "method_not_allowed", "Method not allowed");
await route.fulfill({
status: answer.status,
contentType: answer.status >= 400 ? "application/problem+json" : "application/json",
body: JSON.stringify(answer.body),
});
});
}
test.describe("candidate home states with a stubbed API", () => {
test("shows the declared grade and the confirmed category apart and links to the result and privacy", async ({
page,
}) => {
await mockCandidateApi(page, {
step: "candidate_assessment",
profileVersion: 2,
declared: { specialization: "backend", grade: "middle" },
confirmed: "junior",
results: [realResult("confirmed")],
});
await page.goto("/candidate");
await expect(page.getByRole("heading", { name: "Категория получена" })).toBeVisible();
await expect(page.getByText("Заявлено: Middle")).toBeVisible();
await expect(page.getByText("Подтверждено тестом: Junior")).toBeVisible();
await expect(page.getByText(/Закрыта: компании ее не видят/)).toBeVisible();
await expect(page.getByRole("link", { name: "Открыть результат" })).toHaveAttribute(
"href",
"/candidate/results",
);
await expect(
page.getByRole("link", { name: "Настроить видимость", exact: true }),
).toHaveAttribute("href", "/candidate/privacy");
await expect(page.getByRole("link", { name: "Открыть разбор результата" })).toHaveAttribute(
"href",
`/candidate/results/${attemptId}`,
);
await expect(page.getByRole("alert")).toHaveCount(0);
await expectNoHorizontalOverflow(page);
await captureReviewScreenshots(page, "candidate-home-category");
});
test("states one confirmed category in every block when the availability confirms it", async ({
page,
}) => {
await mockCandidateApi(page, {
step: "candidate_consents",
profileVersion: 1,
declared: { specialization: "backend", grade: "junior" },
confirmed: "junior",
results: [realResult("confirmed")],
});
await page.goto("/candidate");
await expect(page.getByRole("heading", { name: "Категория получена" })).toBeVisible();
await expect(page.getByText("Подтверждено тестом: Junior").first()).toBeVisible();
await expect(page.getByText("Есть подтвержденная категория")).toBeVisible();
await expect(page.getByText("Уровень подтвержден: Backend, Junior.")).toBeVisible();
await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toHaveCount(0);
await expect(page.getByText("Пока не подтверждена")).toHaveCount(0);
await expect(page.getByText("Еще не пройден")).toHaveCount(0);
await expect(page.getByText(/Сохраненный шаг аккаунта/)).toHaveCount(0);
await expect(page.getByRole("alert")).toHaveCount(0);
});
test("shows an open card and an active search status exactly as the API returns them", async ({
page,
}) => {
await mockCandidateApi(page, {
step: "candidate_assessment",
profileVersion: 2,
declared: { specialization: "backend", grade: "junior" },
confirmed: "junior",
results: [realResult("confirmed")],
privacy: {
publication: {
state: "published",
closed_reason: null,
fields: ["categories", "stack"],
consent_id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a81",
published_at: "2026-10-08T10:00:00Z",
version: 2,
},
search_status: {
value: "looking",
lapsed: false,
confirmed_at: "2026-10-08T10:00:00Z",
lapses_at: "2099-11-07T10:00:00Z",
version: 1,
},
hidden_organizations_total: 0,
},
});
await page.goto("/candidate");
await expect(page.getByText("Открыта: компании видят выбранные поля")).toBeVisible();
await expect(page.getByText("Показывается", { exact: true })).toBeVisible();
await expect(page.getByText(/Ищу работу, статус действует до/)).toBeVisible();
});
test("without a category the test stays next and a missing result is not an error", async ({
page,
}) => {
await mockCandidateApi(page, {
step: "candidate_assessment",
profileVersion: 2,
declared: { specialization: "backend", grade: "middle" },
results: [],
});
await page.goto("/candidate");
await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible();
await expect(
page.getByRole("link", { name: "Перейти к тесту", exact: true }).first(),
).toHaveAttribute("href", "/candidate/assessment");
await expect(page.getByText("Пока не подтверждена")).toBeVisible();
await expect(page.getByText(/Подтверждено тестом:/)).toHaveCount(0);
await expect(page.getByText("Завершенных попыток пока нет")).toBeVisible();
await expect(page.getByText(/Привязка ФСП ID необязательна/)).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
await captureReviewScreenshots(page, "candidate-home-no-category");
});
test("a failed attempt keeps the category empty and the test available", async ({ page }) => {
await mockCandidateApi(page, {
step: "candidate_assessment",
profileVersion: 2,
declared: { specialization: "backend", grade: "junior" },
results: [realResult("not_confirmed")],
});
await page.goto("/candidate");
await expect(page.getByText("Уровень пока не подтвержден: Backend, Junior.")).toBeVisible();
await expect(page.getByText("Пока не подтверждена")).toBeVisible();
await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible();
});
test("a failed read shows an error with retry instead of a guessed step", async ({ page }) => {
let fail = true;
await mockCandidateApi(page, {
profileVersion: 1,
declared: { specialization: "backend", grade: "junior" },
});
await page.route("**/api/v1/me/assessment-availability", async (route) => {
if (fail) {
await route.fulfill({
status: 500,
contentType: "application/problem+json",
body: JSON.stringify(problem(500, "internal", "Internal error").body),
});
return;
}
await route.fallback();
});
await page.goto("/candidate");
const alert = page.getByRole("alert");
await expect(alert).toContainText("Не удалось определить следующий шаг");
await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toHaveCount(0);
await expect(page.getByRole("heading", { name: "Заполните профиль" })).toHaveCount(0);
fail = false;
await alert.getByRole("button", { name: "Повторить" }).click();
await expect(page.getByRole("heading", { name: "Подтвердите уровень тестом" })).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
});
test("a denied read shows the forbidden state without a retry", async ({ page }) => {
await mockCandidateApi(page, {
stubs: { "/api/v1/me/profile": problem(403, "forbidden", "Forbidden") },
});
await page.goto("/candidate");
await expect(page.getByText("Нет доступа")).toBeVisible();
await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0);
});
test("a failed privacy read does not hide the next step", async ({ page }) => {
await mockCandidateApi(page, {
profileVersion: 0,
stubs: { "/api/v1/me/privacy": problem(500, "internal", "Internal error") },
});
await page.goto("/candidate");
await expect(page.getByRole("heading", { name: "Заполните профиль" })).toBeVisible();
await expect(
page.getByRole("link", { name: "Заполнить профиль", exact: true }).first(),
).toHaveAttribute("href", "/candidate/profile");
await expect(page.getByRole("alert")).toContainText("Сервис временно недоступен");
});
test("an expired session sends the candidate to sign-in", async ({ page }) => {
await mockCandidateApi(page, {
stubs: {
"/api/v1/identity/sessions/current": problem(401, "unauthenticated", "Unauthenticated"),
},
});
await page.goto("/candidate");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
});
});