Files
lincodex/frontend/e2e/minimal-path-a11y.spec.ts
T

735 lines
33 KiB
TypeScript

import { expect, test, type Locator, type Page, type Request, type Route } from "@playwright/test";
import { expectNoHorizontalOverflow } from "./viewport";
// States, focus, and error binding of the minimal path with a stubbed API. The
// API answers come from this file, so each test controls one failure at a time
// and needs no fixtures on the stand. Every screen is checked at 360, 768, and
// 1280 px: the stubbed content must fit without horizontal scrolling, and each
// control is reached with the Tab key and shows a focus outline.
//
// The last describe block runs against the real backend: it registers a
// candidate through the local mail fixture and checks the unsent assessment
// answer after a reload. The registration helpers are copies of the ones in
// assessment.spec.ts. See docs/en/TESTING.md, "Minimal path states and
// accessibility", for what each part proves.
const widths = [360, 768, 1280] as const;
const accountId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4001";
const invitationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4101";
const organizationId = "0199b4f2-7c1e-7d3a-9f00-aabbccdd4201";
const csrfToken = "A".repeat(43);
const openDeadline = "2099-10-16T10:00:00Z";
test.use({ trace: "off", screenshot: "off", video: "off" });
type Answer = { status: number; body?: unknown; code?: string } | "abort";
type Responder = Answer | ((call: number, request: Request) => Answer | Promise<Answer>);
// Keys are "METHOD /api/v1/path". Each responder sees the number of its calls.
type Routes = Record<string, Responder>;
function candidateSession() {
return {
account: {
id: accountId,
email: "candidate@example.test",
email_verified: true,
scenario: "candidate",
onboarding_step: "completed",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: csrfToken,
};
}
function problem(code: string, status: number): Answer {
return { status, code };
}
const candidateTerms = {
role_title: "Middle Go-разработчик в команду платежей",
specialization: "backend",
grade: "middle",
offer_type: "full_time",
tasks: ["Развивать сервис выплат", "Перевести отчеты на события"],
team: "Пять бэкенд-разработчиков\nи QA-инженер",
tech_stack: ["Go", "PostgreSQL"],
work_formats: ["remote", "hybrid"],
location: "Москва",
communication_method: { channel: "video_call", details: "Созвон с тимлидом" },
salary: {
salary_from: 100000,
salary_to: 140000,
currency: "RUB",
period: "month",
tax_basis: "net",
},
package: {
bonus: { status: "provided", description: "Квартальная премия до 20%" },
equipment: { status: "provided", description: "Ноутбук и монитор" },
training: { status: "not_provided" },
health_insurance: { status: "not_provided" },
},
};
function candidateInvitation(overrides: Record<string, unknown> = {}) {
return {
id: invitationId,
organization: { id: organizationId, name: "Северный ветер" },
state: "delivered",
expiry_reason: null,
version: 1,
terms_version: 1,
terms: candidateTerms,
response_deadline_at: openDeadline,
delivered_at: "2026-10-09T10:00:00Z",
viewed_at: null,
responded_at: null,
updated_at: "2026-10-09T10:00:00Z",
contact_consent: null,
decline: null,
contact_grant: null,
...overrides,
};
}
function inboxItem() {
const invitation = candidateInvitation();
return {
id: invitation.id,
organization: invitation.organization,
state: invitation.state,
expiry_reason: null,
version: 1,
terms_version: 1,
role_title: candidateTerms.role_title,
salary: candidateTerms.salary,
work_formats: candidateTerms.work_formats,
response_deadline_at: openDeadline,
delivered_at: invitation.delivered_at,
viewed_at: null,
updated_at: invitation.updated_at,
};
}
function deferred<T>() {
let resolve: (value: T) => void = () => undefined;
const promise = new Promise<T>((done) => {
resolve = done;
});
return { promise, resolve };
}
// Answers every /api/v1 request from the routes; an unknown request is a 404
// problem, so a missing stub shows up as a failed state instead of a hang.
async function mockApi(page: Page, routes: Routes): Promise<Map<string, number>> {
const calls = new Map<string, number>();
await page.route("**/api/v1/**", async (route: Route) => {
const request = route.request();
const { pathname } = new URL(request.url());
const key = `${request.method()} ${pathname}`;
const count = (calls.get(key) ?? 0) + 1;
calls.set(key, count);
const responder = routes[key];
const answer: Answer =
responder === undefined
? problem("not_found", 404)
: typeof responder === "function"
? await responder(count, request)
: responder;
if (answer === "abort") {
await route.abort("failed");
return;
}
if (answer.status >= 400) {
await route.fulfill({
status: answer.status,
contentType: "application/problem+json",
body: JSON.stringify({
type: `urn:lincodex:problem:${answer.code ?? "error"}`,
title: answer.code ?? "error",
status: answer.status,
code: answer.code ?? "error",
}),
});
return;
}
await route.fulfill({
status: answer.status,
contentType: "application/json",
body: JSON.stringify(answer.body ?? null),
});
});
return calls;
}
// The focus outline comes from the global :focus-visible rule. A control that
// has focus from the keyboard must match that selector and draw an outline.
async function expectFocusOutline(target: Locator): Promise<void> {
const style = await target.evaluate((element) => {
const computed = getComputedStyle(element);
return {
focusVisible: element.matches(":focus-visible"),
outlineStyle: computed.outlineStyle,
outlineWidth: Number.parseFloat(computed.outlineWidth),
};
});
expect(style.focusVisible, "the control matches :focus-visible").toBe(true);
expect(style.outlineStyle, "the focus outline is drawn").not.toBe("none");
expect(style.outlineWidth, "the focus outline has a width").toBeGreaterThan(0);
}
// Moves focus to the target with Tab from the top of the document, as a
// keyboard user does, and checks that the target shows its focus outline.
async function tabTo(page: Page, target: Locator, maxSteps = 80): Promise<void> {
await expect(target).toBeVisible();
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
for (let step = 0; step < maxSteps; step += 1) {
await page.keyboard.press("Tab");
if (await target.evaluate((element) => element === document.activeElement)) {
await expectFocusOutline(target);
return;
}
}
throw new Error("Keyboard navigation did not reach the target control.");
}
test.describe("minimal path states with a stubbed API", () => {
for (const width of widths) {
test(`sign-in at ${width}px: bound field errors and failed answers keep the typed email`, async ({
page,
}) => {
let answers = 0;
await mockApi(page, {
"GET /api/v1/identity/sessions/current": problem("unauthenticated", 401),
"POST /api/v1/identity/sessions": () => {
answers += 1;
return answers === 1
? problem("internal_error", 500)
: problem("invalid_credentials", 401);
},
});
await page.goto("/login");
await expect(page.getByRole("heading", { level: 1, name: "Вход" })).toBeVisible();
await expectNoHorizontalOverflow(page, width);
const email = page.getByLabel("Электронная почта");
const password = page.getByLabel("Пароль", { exact: true });
const submit = page.locator('button[type="submit"]');
// An empty submit binds each message to its field and marks it invalid.
await tabTo(page, submit);
await page.keyboard.press("Enter");
await expect(email).toHaveAttribute("aria-invalid", "true");
await expect(email).toHaveAccessibleDescription(
"Введите корректный адрес электронной почты.",
);
await expect(password).toHaveAttribute("aria-invalid", "true");
await expect(password).toHaveAccessibleDescription("Введите пароль.");
// A server failure is an alert; the typed email stays in place.
await tabTo(page, email);
await page.keyboard.type("candidate@example.test");
await tabTo(page, password);
await page.keyboard.type("correct horse battery staple 2026");
await page.keyboard.press("Enter");
await expect(page.getByRole("alert")).toHaveText(
"Не удалось выполнить вход. Проверьте соединение и повторите попытку.",
);
await expect(email).toHaveValue("candidate@example.test");
await expect(email).not.toHaveAttribute("aria-invalid", "true");
await expect(password).toBeFocused();
await expectNoHorizontalOverflow(page, width);
// A second answer with invalid credentials is a different alert.
await page.keyboard.press("Enter");
await expect(page.getByRole("alert")).toHaveText(
"Не удалось войти. Проверьте адрес и пароль.",
);
await expect(email).toHaveValue("candidate@example.test");
await expect(submit).toHaveText("Войти");
await expectNoHorizontalOverflow(page, width);
});
test(`sign-in at ${width}px: a pending answer keeps the focus in the form and reads as busy`, async ({
page,
}) => {
const release = deferred<Answer>();
await mockApi(page, {
"GET /api/v1/identity/sessions/current": problem("unauthenticated", 401),
"POST /api/v1/identity/sessions": () => release.promise,
});
await page.goto("/login");
await expectNoHorizontalOverflow(page, width);
const email = page.getByLabel("Электронная почта");
const password = page.getByLabel("Пароль", { exact: true });
const submit = page.locator('button[type="submit"]');
await tabTo(page, email);
await page.keyboard.type("candidate@example.test");
await tabTo(page, password);
await page.keyboard.type("correct horse battery staple 2026");
await page.keyboard.press("Enter");
await expect(submit).toHaveText("Входим...");
await expect(submit).toHaveAttribute("aria-busy", "true");
await expect(
page.getByRole("status").filter({ hasText: "Проверяем учетные данные" }),
).toBeVisible();
// A read-only field keeps the keyboard focus while the answer is pending.
await expect(password).toBeFocused();
await expect(password).toHaveAttribute("readonly", "");
release.resolve(problem("invalid_credentials", 401));
await expect(page.getByRole("alert")).toHaveText(
"Не удалось войти. Проверьте адрес и пароль.",
);
await expect(submit).toHaveText("Войти");
await expect(password).not.toHaveAttribute("readonly");
});
test(`candidate inbox at ${width}px: loading, error with a keyboard retry, empty, and forbidden`, async ({
page,
}) => {
const gate = deferred<void>();
let failing = true;
await mockApi(page, {
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
"GET /api/v1/me/invitations": async () => {
await gate.promise;
return failing
? problem("internal_error", 500)
: { status: 200, body: { items: [], page: { has_more: false, next_cursor: null } } };
},
});
await page.goto("/candidate/invitations");
await expectNoHorizontalOverflow(page, width);
await expect(page.getByText("Загружаем приглашения...")).toBeVisible();
gate.resolve();
// Queries retry server errors twice, so the error appears after the retries.
await expect(page.getByRole("alert")).toContainText("Не удалось загрузить приглашения", {
timeout: 15_000,
});
failing = false;
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
await page.keyboard.press("Enter");
await expect(page.getByText("Приглашений пока нет")).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
await expectNoHorizontalOverflow(page, width);
});
test(`candidate inbox at ${width}px: a dropped connection is named and can be retried`, async ({
page,
}) => {
let online = false;
await mockApi(page, {
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
"GET /api/v1/me/invitations": () =>
online
? { status: 200, body: { items: [], page: { has_more: false, next_cursor: null } } }
: "abort",
});
await page.goto("/candidate/invitations");
// A network error is retried like a server error, so the message follows the retries.
await expect(page.getByRole("alert")).toContainText("Не удалось загрузить приглашения", {
timeout: 15_000,
});
await expect(page.getByRole("alert")).toContainText("Проверьте подключение к интернету");
await expectNoHorizontalOverflow(page, width);
online = true;
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
await page.keyboard.press("Enter");
await expect(page.getByText("Приглашений пока нет")).toBeVisible();
});
test(`candidate inbox at ${width}px: a forbidden answer shows no retry`, async ({ page }) => {
await mockApi(page, {
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
"GET /api/v1/me/invitations": problem("forbidden", 403),
});
await page.goto("/candidate/invitations");
await expect(page.getByText("Нет доступа")).toBeVisible();
await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0);
await expectNoHorizontalOverflow(page, width);
});
test(`candidate inbox at ${width}px: an invitation card names the company, the role, and the state in text`, async ({
page,
}) => {
await mockApi(page, {
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
"GET /api/v1/me/invitations": {
status: 200,
body: { items: [inboxItem()], page: { has_more: false, next_cursor: null } },
},
});
await page.goto("/candidate/invitations");
const list = page.getByRole("region", { name: "Список приглашений" });
await expect(list).toBeVisible();
await expect(list).toContainText("Северный ветер");
await expect(list).toContainText("Middle Go-разработчик в команду платежей");
await expect(list).toContainText("Ждет вашего решения");
await expectNoHorizontalOverflow(page, width);
await tabTo(page, list.getByRole("link").first());
});
test(`candidate invitation at ${width}px: an error with a retry, then a failed decline keeps the comment`, async ({
page,
}) => {
let failing = true;
let declines = 0;
await mockApi(page, {
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
[`GET /api/v1/me/invitations/${invitationId}`]: () =>
failing ? problem("internal_error", 500) : { status: 200, body: candidateInvitation() },
[`POST /api/v1/me/invitations/${invitationId}/view`]: {
status: 200,
body: candidateInvitation({ state: "viewed", viewed_at: "2026-10-09T10:05:00Z" }),
},
[`POST /api/v1/me/invitations/${invitationId}/decline`]: () => {
declines += 1;
if (declines === 1) return problem("internal_error", 500);
return {
status: 200,
body: candidateInvitation({
state: "declined",
version: 2,
responded_at: "2026-10-09T10:06:00Z",
decline: {
reason: "salary",
comment: "Ждали вилку выше.",
declined_at: "2026-10-09T10:06:00Z",
},
}),
};
},
});
await page.goto(`/candidate/invitations/${invitationId}`);
await expect(page.getByRole("alert")).toContainText("Не удалось открыть приглашение", {
timeout: 15_000,
});
failing = false;
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
await page.keyboard.press("Enter");
await expect(page.getByRole("heading", { level: 1, name: "Приглашение" })).toBeVisible();
await expectNoHorizontalOverflow(page, width);
await tabTo(page, page.getByLabel("Вилка зарплаты не подходит"));
await page.keyboard.press("Space");
const comment = page.getByLabel("Комментарий (необязательно)");
await tabTo(page, comment);
await page.keyboard.type("Ждали вилку выше.");
const decline = page.getByRole("button", { name: "Отклонить приглашение" });
await tabTo(page, decline);
await page.keyboard.press("Enter");
const alert = page.getByRole("alert");
await expect(alert).toBeVisible();
await expect(alert).toBeFocused();
await expect(comment).toHaveValue("Ждали вилку выше.");
await expect(page.getByLabel("Вилка зарплаты не подходит")).toBeChecked();
await expectNoHorizontalOverflow(page, width);
await tabTo(page, decline);
await page.keyboard.press("Enter");
await expect(page.getByText("Вы отклонили приглашение").first()).toBeVisible();
await expect(page.getByRole("button", { name: "Отклонить приглашение" })).toHaveCount(0);
await expectNoHorizontalOverflow(page, width);
});
test(`assessment availability at ${width}px: an error with a retry, then the empty specialization state`, async ({
page,
}) => {
let failing = true;
await mockApi(page, {
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
"GET /api/v1/me/assessment-availability": () =>
failing ? problem("internal_error", 500) : { status: 200, body: { specializations: [] } },
"GET /api/v1/me/questionnaire": {
status: 200,
body: { version: 0, specializations: [], work_context: null, updated_at: null },
},
});
await page.goto("/candidate/assessment");
await expect(page.getByRole("alert")).toContainText(
"Не удалось загрузить состояние проверки",
{ timeout: 15_000 },
);
await expectNoHorizontalOverflow(page, width);
failing = false;
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
await page.keyboard.press("Enter");
await expect(page.getByText("Сначала выберите специализацию")).toBeVisible();
await expect(page.getByRole("link", { name: "Открыть анкету" })).toBeVisible();
await expectNoHorizontalOverflow(page, width);
});
test(`candidate profile at ${width}px: loading, an error with a retry, and access denied`, async ({
page,
}) => {
// The profile query does not retry, so the state changes only when the
// candidate presses the retry button: the second answer is a 403.
const release = deferred<void>();
let stage: "error" | "forbidden" = "error";
await mockApi(page, {
"GET /api/v1/identity/sessions/current": { status: 200, body: candidateSession() },
"GET /api/v1/me/profile": async () => {
await release.promise;
return stage === "error" ? problem("internal_error", 500) : problem("forbidden", 403);
},
});
await page.goto("/candidate/profile");
await expect(page.getByText("Загружаем профиль кандидата...")).toBeVisible();
await expectNoHorizontalOverflow(page, width);
release.resolve();
await expect(page.getByRole("alert")).toContainText("Не удалось загрузить профиль");
stage = "forbidden";
await tabTo(page, page.getByRole("button", { name: "Повторить" }));
await page.keyboard.press("Enter");
await expect(page.getByText("Профиль недоступен")).toBeVisible();
await expect(page.getByRole("button", { name: "Повторить" })).toHaveCount(0);
await expectNoHorizontalOverflow(page, width);
});
}
});
// Real-backend part. It needs the mail fixture for registration and the
// questionnaire fixture for a reviewed assessment bank, so it runs only in
// `make -C deploy test-e2e-registration`, like the assessment specs.
type InboxMessage = { text?: string; html?: string };
type InboxResponse = { messages: InboxMessage[] };
type AttemptSnapshot = { id: string; version: number; current_item: { id: string } | null };
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1";
const password = "correct horse battery staple 2026";
const draftKeyPrefix = "lincodex.assessment-answer-draft.v1:";
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 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 waitForVerificationMessage(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 registerVerifiedCandidate(page: Page): Promise<string> {
const email = `assessment-${crypto.randomUUID()}@example.test`;
await page.goto("/register");
await expect(
page.getByRole("heading", { name: "Согласие C1 на обработку персональных данных" }),
).toBeVisible();
await expect(page.getByText(/C4/)).toHaveCount(0);
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 message = await waitForVerificationMessage(email);
const verificationUrl = new URL("/verify-email", baseUrl());
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await expect.poll(() => page.evaluate(() => window.location.hash)).toBe("");
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
const confirmResponse = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/email-verifications",
);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
expect((await confirmResponse).status()).toBe(200);
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await page.goto("/candidate/questionnaire");
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);
return email;
}
async function grantC3(page: Page): Promise<void> {
await page.goto("/candidate/privacy");
await page.getByRole("button", { name: "Прочитать текущий текст C3" }).click();
await page.getByLabel("Я прочитал(а) и принимаю только это согласие C3.").check();
const response = page.waitForResponse(
(item) =>
item.request().method() === "PUT" &&
new URL(item.url()).pathname === "/api/v1/me/consents/c3",
);
await page.getByRole("button", { name: "Дать согласие C3" }).click();
expect((await response).status()).toBe(200);
}
async function saveAssessmentQuestionnaire(page: Page): Promise<void> {
await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
// The questionnaire is a form in steps; "Далее" moves the focus to the next heading.
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("junior");
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
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 response = page.waitForResponse(
(item) =>
item.request().method() === "PUT" &&
new URL(item.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await response).status()).toBe(200);
}
// Waits for the control, then walks the Tab order to it with the keyboard and
// checks its focus outline. The control can appear after a save, so the wait is
// longer than the default expectation on a loaded stand.
async function focusWithKeyboard(page: Page, target: Locator): Promise<void> {
await expect(target).toBeVisible({ timeout: 20_000 });
await tabTo(page, target, 120);
}
test.describe("minimal path with the real backend", () => {
test.skip(
!mailFixtureEnabled || !questionnaireFixtureEnabled,
"Requires the isolated reviewed assessment-bank and mail fixtures.",
);
test("an unsent answer on a phone survives a reload, and an accepted answer clears it", async ({
page,
}) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 360, height: 800 });
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");
const createResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/me/assessment-attempts",
);
await focusWithKeyboard(page, page.getByRole("button", { name: "Начать полную проверку" }));
await page.keyboard.press("Enter");
await expect(page.getByRole("dialog", { name: /какие сигналы собираются/ })).toBeVisible();
await focusWithKeyboard(
page,
page.getByRole("button", { name: "Подтверждаю ознакомление и начинаю" }),
);
await page.keyboard.press("Enter");
const createResponse = await createResponsePromise;
expect(createResponse.status()).toBe(201);
const attempt = (await createResponse.json()) as AttemptSnapshot;
await expect(page).toHaveURL(new RegExp(`/candidate/assessment/${attempt.id}$`));
const startPromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${attempt.id}/sessions`,
);
await focusWithKeyboard(page, page.getByRole("button", { name: "Начать или продолжить" }));
await page.keyboard.press("Enter");
expect((await startPromise).status()).toBe(200);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
// The typed answer is not sent: the candidate reloads before submitting it.
const answer = page.getByRole("textbox", { name: /^Числовой ответ/ });
await focusWithKeyboard(page, answer);
await page.keyboard.type("42");
await expect
.poll(() =>
page.evaluate(
(prefix) =>
Object.keys(window.sessionStorage).filter((key) => key.startsWith(prefix)).length,
draftKeyPrefix,
),
)
.toBe(1);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
const reloadPromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}`,
);
await page.reload();
expect((await reloadPromise).status()).toBe(200);
const resumePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname ===
`/api/v1/me/assessment-attempts/${attempt.id}/sessions`,
);
await focusWithKeyboard(page, page.getByRole("button", { name: "Начать или продолжить" }));
await page.keyboard.press("Enter");
expect((await resumePromise).status()).toBe(200);
await expect(page.getByRole("heading", { name: "Задание 1" })).toBeVisible();
await expect(page.getByRole("textbox", { name: /^Числовой ответ/ })).toHaveValue("42");
await expectNoHorizontalOverflow(page, 768);
await expectNoHorizontalOverflow(page, 360);
// An accepted answer moves to the next item and removes the stored draft.
const answerPromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === `/api/v1/me/assessment-attempts/${attempt.id}/answers`,
);
await focusWithKeyboard(page, page.getByRole("button", { name: "Отправить ответ" }));
await page.keyboard.press("Enter");
expect((await answerPromise).status()).toBe(200);
await expect(page.getByRole("heading", { name: "Задание 2" })).toBeVisible();
await expect
.poll(() =>
page.evaluate(
(prefix) =>
Object.keys(window.sessionStorage).filter((key) => key.startsWith(prefix)).length,
draftKeyPrefix,
),
)
.toBe(0);
});
});