feat(candidate): add the candidate home, results and result history screens
This commit is contained in:
1 parent
8277133712
commit
4761508f13
52 files changed
+5334
-81
No files matched your search
@@ -1,4 +1,12 @@
|
||||
import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test";
|
||||
import {
|
||||
expect,
|
||||
test,
|
||||
type Locator,
|
||||
type Page,
|
||||
type Request,
|
||||
type Response,
|
||||
type Route,
|
||||
} from "@playwright/test";
|
||||
|
||||
type InboxMessage = {
|
||||
text?: string;
|
||||
@@ -57,7 +65,7 @@ function verificationToken(message: InboxMessage): string {
|
||||
return token;
|
||||
}
|
||||
|
||||
async function registerVerifiedCandidate(page: Page): Promise<void> {
|
||||
async function registerVerifiedCandidate(page: Page): Promise<string> {
|
||||
const email = `assessment-${crypto.randomUUID()}@example.test`;
|
||||
await page.goto("/register");
|
||||
await expect(
|
||||
@@ -98,6 +106,7 @@ async function registerVerifiedCandidate(page: Page): Promise<void> {
|
||||
);
|
||||
await page.getByRole("button", { name: "Войти" }).click();
|
||||
expect((await loginResponse).status()).toBe(201);
|
||||
return email;
|
||||
}
|
||||
|
||||
async function grantC3(page: Page): Promise<void> {
|
||||
@@ -846,3 +855,209 @@ test("a failed signal batch is retried with the same key while the answer is sav
|
||||
await page.waitForTimeout(3_000);
|
||||
expect(signalRequests.filter((item) => item.key === first?.key)).toHaveLength(2);
|
||||
});
|
||||
|
||||
const resultHeading = "Результат с сервера";
|
||||
const expressBanner =
|
||||
"Демонстрация завершена. Она не подтверждает квалификацию и не присваивает грейд.";
|
||||
|
||||
function isFinalizeResponse(response: Response, attemptId: string): boolean {
|
||||
return (
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attemptId}/finalize`
|
||||
);
|
||||
}
|
||||
|
||||
/** Creates an attempt from the assessment page, resumes it, and answers every item. */
|
||||
async function runAttemptToResult(
|
||||
page: Page,
|
||||
start: { name: string; confirmNotice: boolean },
|
||||
): Promise<string> {
|
||||
const createResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === "/api/v1/me/assessment-attempts",
|
||||
);
|
||||
await page.getByRole("button", { name: start.name }).click();
|
||||
if (start.confirmNotice) await page.getByRole("button", { name: confirmNoticeName }).click();
|
||||
const attempt = (await (await createResponse).json()) as AttemptSnapshot;
|
||||
await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`));
|
||||
|
||||
const resumeResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "POST" &&
|
||||
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/sessions`,
|
||||
);
|
||||
await page.getByRole("button", { name: "Начать или продолжить" }).click();
|
||||
const resumed = (await (await resumeResponse).json()) as AttemptSnapshot;
|
||||
await answerRequiredNumericItems(page, attempt.id, resumed.progress.max_items);
|
||||
|
||||
const finalizeResponse = page.waitForResponse((response) =>
|
||||
isFinalizeResponse(response, attempt.id),
|
||||
);
|
||||
await page.getByRole("button", { name: "Завершить проверку" }).click();
|
||||
expect((await finalizeResponse).status()).toBe(200);
|
||||
await expect(page.getByRole("heading", { name: resultHeading })).toBeVisible();
|
||||
return attempt.id;
|
||||
}
|
||||
|
||||
async function signOut(page: Page): Promise<void> {
|
||||
const status = await page.evaluate(async () => {
|
||||
const current = await fetch("/api/v1/identity/sessions/current", {
|
||||
credentials: "same-origin",
|
||||
});
|
||||
const session = (await current.json()) as { csrf_token: string };
|
||||
const response = await fetch("/api/v1/identity/sessions/current", {
|
||||
method: "DELETE",
|
||||
credentials: "same-origin",
|
||||
headers: { "X-CSRF-Token": session.csrf_token },
|
||||
});
|
||||
return response.status;
|
||||
});
|
||||
expect(status).toBe(204);
|
||||
}
|
||||
|
||||
async function signIn(page: Page, email: string): Promise<void> {
|
||||
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);
|
||||
}
|
||||
|
||||
// Browser coverage here is the shape of the flow (a real result, the express
|
||||
// run, ownership, and sign-out). The stand cannot produce a failed attempt
|
||||
// after a successful one or an adaptive estimate, so those values, the retry
|
||||
// dates, and the missing-field cases are covered by the unit fixtures.
|
||||
test("results keep the express run apart and stay private to the signed-in candidate", async ({
|
||||
page,
|
||||
browser,
|
||||
}) => {
|
||||
test.skip(
|
||||
!questionnaireFixtureEnabled || !mailFixtureEnabled,
|
||||
"Requires the isolated reviewed assessment-bank and mail fixtures.",
|
||||
);
|
||||
test.setTimeout(240_000);
|
||||
|
||||
const email = await registerVerifiedCandidate(page);
|
||||
await grantC3(page);
|
||||
await saveAssessmentQuestionnaire(page);
|
||||
await page.goto("/candidate/assessment");
|
||||
await expect(page.getByRole("heading", { name: "Проверка знаний" })).toBeVisible();
|
||||
await page.getByLabel("Язык задания").selectOption("python");
|
||||
|
||||
// The full result: method, date, category state, and the provisional status.
|
||||
const realResult = page.waitForResponse(
|
||||
(response) =>
|
||||
response.request().method() === "GET" &&
|
||||
response.status() === 200 &&
|
||||
/^\/api\/v1\/me\/assessment-attempts\/[^/]+\/result$/.test(new URL(response.url()).pathname),
|
||||
);
|
||||
const realId = await runAttemptToResult(page, {
|
||||
name: "Начать полную проверку",
|
||||
confirmNotice: true,
|
||||
});
|
||||
const stored = (await (await realResult).json()) as { mode: "demo_basic" | "adaptive" };
|
||||
// Only a short phrase is a live message; the record is ordinary content and
|
||||
// the focus moved to its heading.
|
||||
await expect(page.getByRole("heading", { name: resultHeading })).toBeFocused();
|
||||
await expect(page.getByRole("status").filter({ hasText: "Результат получен" })).toHaveCount(1);
|
||||
await expect(page.getByRole("status").getByRole("article")).toHaveCount(0);
|
||||
const inline = page.getByRole("article");
|
||||
await expect(inline.getByText("Метод и ограничения")).toBeVisible();
|
||||
await expect(inline.getByText("Категория после этого результата", { exact: true })).toBeVisible();
|
||||
await expect(inline.getByText("Дата решения", { exact: true })).toBeVisible();
|
||||
await expect(inline.getByText("Предварительный результат")).toBeVisible();
|
||||
if (stored.mode === "demo_basic") {
|
||||
await expect(inline.getByText(/Перцентиль, оценка способности, интервал/)).toBeVisible();
|
||||
await expect(inline.getByText("Стандартная ошибка (SE)")).toHaveCount(0);
|
||||
}
|
||||
await expect(page.getByRole("link", { name: "Открыть на странице результатов" })).toHaveAttribute(
|
||||
"href",
|
||||
`/candidate/results/${realId}`,
|
||||
);
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
await expectNoHorizontalOverflow(page, 1280);
|
||||
|
||||
// The express run is a demonstration: no category, and it offers the full test.
|
||||
await page.goto("/candidate/assessment");
|
||||
await expect(page.getByRole("button", { name: "Начать демонстрацию" })).toBeVisible();
|
||||
const expressId = await runAttemptToResult(page, {
|
||||
name: "Начать демонстрацию",
|
||||
confirmNotice: false,
|
||||
});
|
||||
await expect(page.getByText(expressBanner)).toBeVisible();
|
||||
await expect(page.getByText("не присваивается", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(/Подтвержденный уровень/)).toHaveCount(0);
|
||||
await page.getByRole("link", { name: "Перейти к полной проверке" }).click();
|
||||
await expect(page).toHaveURL(/\/candidate\/assessment$/);
|
||||
await expect(page.getByRole("heading", { name: "Проверка знаний", level: 1 })).toBeVisible();
|
||||
|
||||
// History: only the real result; the express run does not replace or join it.
|
||||
await page.goto("/candidate/results");
|
||||
await expect(page.getByRole("heading", { name: "Результаты проверок", level: 1 })).toBeVisible();
|
||||
const history = page.getByRole("list", { name: "История результатов" });
|
||||
await expect(history.getByRole("listitem")).toHaveCount(1);
|
||||
await expect(history.getByRole("link")).toHaveAttribute("href", `/candidate/results/${realId}`);
|
||||
await expect(page.locator(`a[href$="${expressId}"]`)).toHaveCount(0);
|
||||
await expect(page.getByText(/Демонстрационные запуски сюда не попадают/)).toBeVisible();
|
||||
await expectNoHorizontalOverflow(page, 360);
|
||||
await page.screenshot({
|
||||
path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/assessment-history-360.png`,
|
||||
animations: "disabled",
|
||||
});
|
||||
await expectNoHorizontalOverflow(page, 1280);
|
||||
|
||||
// The stored real result opens by its URL and is not a demonstration.
|
||||
await history.getByRole("link").click();
|
||||
await expect(page).toHaveURL(new RegExp(`/candidate/results/${realId}$`));
|
||||
await expect(page.getByRole("heading", { name: "Результат проверки", level: 1 })).toBeVisible();
|
||||
await expect(page.getByText("Основная проверка", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText(expressBanner)).toHaveCount(0);
|
||||
|
||||
// The express result opens by its own URL, still without a category.
|
||||
await page.goto(`/candidate/results/${expressId}`);
|
||||
await expect(page.getByText(expressBanner)).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "Перейти к полной проверке" })).toBeVisible();
|
||||
|
||||
// Another candidate cannot read the history or the result by a direct URL.
|
||||
const otherContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
|
||||
try {
|
||||
const other = await otherContext.newPage();
|
||||
await registerVerifiedCandidate(other);
|
||||
await other.goto("/candidate/results");
|
||||
await expect(other.getByText("Результатов пока нет")).toBeVisible();
|
||||
await expect(other.locator(`a[href$="${realId}"]`)).toHaveCount(0);
|
||||
await other.goto(`/candidate/results/${realId}`);
|
||||
await expect(other.getByText("Результат недоступен")).toBeVisible();
|
||||
await expect(other.getByText("Метод и ограничения")).toHaveCount(0);
|
||||
} finally {
|
||||
await otherContext.close();
|
||||
}
|
||||
|
||||
// After sign-out the SPA keeps its in-memory state. The app has no sign-out
|
||||
// control yet, so the session ends through the API; moving inside the app
|
||||
// must then show no stored data, and a fresh load must ask for sign-in.
|
||||
await navigateInApp(page, "/candidate/results");
|
||||
await expect(history.getByRole("listitem")).toHaveCount(1);
|
||||
await signOut(page);
|
||||
expect((await page.request.get("/api/v1/me/assessment-results")).status()).toBe(401);
|
||||
await navigateInApp(page, `/candidate/results/${realId}`);
|
||||
await expect(page.getByText(/недоступ/).first()).toBeVisible();
|
||||
await expect(page.getByText("Метод и ограничения")).toHaveCount(0);
|
||||
await navigateInApp(page, "/candidate/results");
|
||||
await expect(page.getByText(/недоступ/).first()).toBeVisible();
|
||||
await expect(history.getByRole("listitem")).toHaveCount(0);
|
||||
await page.goto(`/candidate/results/${realId}`);
|
||||
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
|
||||
await expect(page.getByText("Метод и ограничения")).toHaveCount(0);
|
||||
|
||||
// Signing in again restores the permitted screen.
|
||||
await signIn(page, email);
|
||||
await navigateInApp(page, "/candidate/results");
|
||||
await expect(history.getByRole("listitem")).toHaveCount(1);
|
||||
});
|
||||
@@ -0,0 +1,577 @@
|
||||
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("Тестовый кандидат");
|
||||
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.getByLabel("Моя оценка уровня").selectOption("middle");
|
||||
await page.getByRole("checkbox", { name: "Python", exact: true }).check();
|
||||
await page.getByRole("checkbox", { name: "Удаленно", exact: true }).check();
|
||||
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 } };
|
||||
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,
|
||||
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/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("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();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user