feat: add candidate profile, questionnaire and company forms

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 16:07:02 +03:00
1 parent 3a61a8e8bb
commit f81cd0ae09
68 files changed
+9517 -54

No files matched your search

+1 -1
View File
@@ -96,7 +96,7 @@ test.describe("registration, email confirmation, and onboarding", () => {
const email = `auth-${crypto.randomUUID()}@example.test`;
const password = "correct horse battery staple 2026";
const scenarioLabel = scenario === "candidate" ? "Кандидат" : "Работодатель";
const nextStep = scenario === "candidate" ? "Согласия" : "Компания и команда";
const nextStep = scenario === "candidate" ? "Согласия" : "Компания";
await page.goto("/register");
await expect(
+457
View File
@@ -0,0 +1,457 @@
import { expect, test, type Page } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
type OrganizationResponse = {
id: string;
name: string;
version: number;
candidate_card: {
name: string;
description: string | null;
sphere: string | null;
contacts: Record<string, string | null>;
representatives?: { name: string; job_title: string }[] | null;
verification_level: string;
};
};
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
type CurrentSessionResponse = {
account: { id: string };
};
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 expected 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 registerVerifiedEmployer(
page: Page,
): Promise<{ email: string; password: string; userId: string }> {
const suffix = crypto.randomUUID().slice(0, 8);
const email = `company-${suffix}@example.test`;
const password = "correct horse battery staple 2026";
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 message = await waitForVerificationMessage(email);
const verificationUrl = new URL("/verify-email", process.env.E2E_BASE_URL);
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await page.goto("/employer/company");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
const loginResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
response.status() === 201,
);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: "Компания" })).toBeVisible();
const loginResponse = await loginResponsePromise;
const currentSession = (await loginResponse.json()) as CurrentSessionResponse;
return { email, password, userId: currentSession.account.id };
}
async function revokeCompanyMembership(
organizationId: string,
userId: string,
successorUserId: string,
): Promise<void> {
const fixtureURL = process.env.E2E_COMPANY_FIXTURE_URL;
const fixtureToken = process.env.E2E_COMPANY_FIXTURE_TOKEN;
if (!fixtureURL || !fixtureToken) {
throw new Error("The local company membership fixture is not configured.");
}
const response = await fetch(new URL(fixtureURL), {
method: "POST",
headers: {
Authorization: `Bearer ${fixtureToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
organization_id: organizationId,
user_id: userId,
successor_user_id: successorUserId,
}),
});
if (response.status !== 204) {
throw new Error("The local company membership fixture could not revoke the test membership.");
}
}
function isOrganizationRead(response: { url(): string; request(): { method(): string } }): boolean {
return (
response.request().method() === "GET" &&
/\/api\/v1\/organizations\/[0-9a-f-]+$/.test(new URL(response.url()).pathname)
);
}
test.use({ trace: "off", screenshot: "off", video: "off" });
test.describe("company cabinet", () => {
test.skip(
!mailFixtureEnabled || !companyFixtureEnabled,
"Requires the isolated mail and company fixtures.",
);
test("creates, retries, edits, reloads, previews, and hides data after membership revocation", async ({
browser,
page,
}) => {
const { email, userId } = await registerVerifiedEmployer(page);
const baseURL = process.env.E2E_BASE_URL;
if (!baseURL) throw new Error("The local browser test origin is not configured.");
const successorContext = await browser.newContext({
baseURL,
locale: "ru-RU",
});
let successorUserId: string;
try {
const successorPage = await successorContext.newPage();
successorUserId = (await registerVerifiedEmployer(successorPage)).userId;
} finally {
await successorContext.close();
}
const suffix = crypto.randomUUID().slice(0, 8);
const companyName = `North Star ${suffix}`;
const companyDescription = `Candidate-facing company profile ${suffix}`;
const companyMailbox = `careers-${suffix}@example.test`;
const createAttempts: { key: string | undefined; csrf: string | undefined; body: unknown }[] =
[];
const updateAttempts: { csrf: string | undefined; body: unknown }[] = [];
let firstResponseLost = false;
await page.route("**/api/v1/organizations", async (route) => {
if (route.request().method() !== "POST") {
await route.continue();
return;
}
createAttempts.push({
key: route.request().headers()["idempotency-key"],
csrf: route.request().headers()["x-csrf-token"],
body: route.request().postDataJSON(),
});
if (!firstResponseLost) {
const response = await route.fetch();
expect(response.status()).toBe(201);
firstResponseLost = true;
await route.fulfill({
status: 502,
contentType: "application/problem+json; charset=utf-8",
body: JSON.stringify({
type: "urn:lincodex:problem:upstream_unavailable",
title: "Temporary response failure",
status: 502,
code: "upstream_unavailable",
}),
});
return;
}
await route.continue();
});
await expect(page.getByText("Компаний пока нет", { exact: true })).toBeVisible();
await page.getByLabel("Название компании").fill(companyName);
await page.getByLabel("Чем занимается компания").fill(companyDescription);
await page.getByLabel("Сфера деятельности").fill("Платежные технологии");
await page.getByLabel("Сайт компании").fill(`https://north-${suffix}.example`);
await page.getByLabel("Почта для связи").fill(companyMailbox);
await page.getByRole("button", { name: "Добавить представителя" }).click();
await page.getByLabel("Имя представителя").fill("Анна Иванова");
await page.getByLabel("Должность").fill("Руководитель по подбору");
await page.getByRole("button", { name: "Создать компанию" }).click();
await expect(
page.getByRole("button", { name: "Повторить создание с теми же данными" }),
).toBeVisible();
const createdResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "POST" &&
new URL(response.url()).pathname === "/api/v1/organizations" &&
response.status() === 201,
);
const firstProfileResponsePromise = page.waitForResponse(
(response) => isOrganizationRead(response) && response.status() === 200,
);
await page.getByRole("button", { name: "Повторить создание с теми же данными" }).click();
const createdResponse = await createdResponsePromise;
expect(createAttempts).toHaveLength(2);
expect(createAttempts[0]?.key).toBeTruthy();
expect(createAttempts[0]?.csrf).toBeTruthy();
expect(createAttempts[1]).toEqual(createAttempts[0]);
const created = (await createdResponse.json()) as OrganizationResponse;
expect(created.name).toBe(companyName);
const firstProfileResponse = await firstProfileResponsePromise;
let firstProfile = (await firstProfileResponse.json()) as OrganizationResponse;
expect(firstProfile.id).toBe(created.id);
const draftName = `${companyName} draft`;
await page.getByLabel("Название компании").fill(draftName);
const revalidationResponsePromise = page.waitForResponse(
(response) => isOrganizationRead(response) && response.status() === 200,
);
await page.getByRole("button", { name: "Обновить профиль" }).click();
await revalidationResponsePromise;
await expect(page.getByLabel("Название компании")).toHaveValue(draftName);
await expect(page.getByText("E0 - подтверждена почта владельца")).toBeVisible();
await expect(page.getByText("Подтвержденная почта владельца")).toBeVisible();
await expect(
page.getByRole("button", { name: /повысить уровень|повысить доверие/i }),
).toHaveCount(0);
const updatedName = `${companyName} Labs`;
await page.getByLabel("Название компании").fill(updatedName);
let csrfFailureReturned = false;
let stalePatchReturned = false;
await page.route(`**/api/v1/organizations/${created.id}`, async (route) => {
if (route.request().method() === "PATCH") {
updateAttempts.push({
csrf: route.request().headers()["x-csrf-token"],
body: route.request().postDataJSON(),
});
}
if (route.request().method() === "PATCH" && !csrfFailureReturned) {
csrfFailureReturned = true;
await route.fulfill({
status: 403,
contentType: "application/problem+json; charset=utf-8",
body: JSON.stringify({
type: "urn:lincodex:problem:csrf_check_failed",
title: "CSRF check failed",
status: 403,
code: "csrf_check_failed",
}),
});
return;
}
if (route.request().method() === "PATCH" && !stalePatchReturned) {
stalePatchReturned = true;
await route.fulfill({
status: 412,
contentType: "application/problem+json; charset=utf-8",
body: JSON.stringify({
type: "urn:lincodex:problem:version_conflict",
title: "Version conflict",
status: 412,
code: "version_conflict",
}),
});
return;
}
await route.continue();
});
const conflictResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PATCH" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 412,
);
const refreshedSessionPromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/identity/sessions/current" &&
response.status() === 200,
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
await expect(page.getByRole("alert")).toContainText("Проверка входа обновлена");
await refreshedSessionPromise;
await expect(page.getByLabel("Название компании")).toHaveValue(updatedName);
expect(updateAttempts).toHaveLength(1);
expect(updateAttempts[0]?.csrf).toBeTruthy();
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const conflictResponse = await conflictResponsePromise;
expect(conflictResponse.status()).toBe(412);
expect(updateAttempts).toHaveLength(2);
expect(updateAttempts[1]?.body).toEqual(updateAttempts[0]?.body);
await expect(page.getByLabel("Название компании")).toHaveValue(updatedName);
const latestProfileResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 200,
);
await page.getByRole("button", { name: "Прочитать текущую версию" }).click();
await latestProfileResponsePromise;
await expect(page.getByLabel("Название компании")).toHaveValue(updatedName);
await page.getByRole("button", { name: "Я проверил черновик" }).click();
const updateResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PATCH" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 200,
);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
const updateResponse = await updateResponsePromise;
expect(updateResponse.status()).toBe(200);
expect(updateAttempts[2]?.csrf).toBeTruthy();
firstProfile = (await updateResponse.json()) as OrganizationResponse;
expect(firstProfile.version).toBeGreaterThan(created.version);
await page.unroute(`**/api/v1/organizations/${created.id}`);
const preview = page.getByRole("article", { name: "Предпросмотр карточки компании" });
await expect(
preview.getByRole("heading", { name: firstProfile.candidate_card.name }),
).toBeVisible();
await expect(
preview.getByText(firstProfile.candidate_card.description ?? "", { exact: true }),
).toBeVisible();
await expect(preview.getByText(companyMailbox, { exact: true })).toBeVisible();
await expect(preview.getByText("Анна Иванова", { exact: true })).toBeVisible();
const previewText = await preview.innerText();
expect(previewText).not.toMatch(/membership|role|участник|владелец/i);
const reloadedProfileResponsePromise = page.waitForResponse(
(response) => isOrganizationRead(response) && response.status() === 200,
);
await page.reload();
const reloadedProfileResponse = await reloadedProfileResponsePromise;
const reloadedProfile = (await reloadedProfileResponse.json()) as OrganizationResponse;
expect(reloadedProfile.id).toBe(created.id);
expect(reloadedProfile.candidate_card).toEqual(firstProfile.candidate_card);
await expect(page.getByRole("heading", { name: updatedName })).toBeVisible();
await expect(
page.getByRole("article", { name: "Предпросмотр карточки компании" }),
).toContainText(reloadedProfile.candidate_card.name);
await expect(page.getByText(email, { exact: true })).toHaveCount(0);
await page.screenshot({
path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/company-profile.png`,
animations: "disabled",
});
let releaseLateUpdate: (() => void) | undefined;
let notifyLateUpdateStarted: (() => void) | undefined;
const lateUpdateGate = new Promise<void>((resolve) => {
releaseLateUpdate = resolve;
});
const lateUpdateStarted = new Promise<void>((resolve) => {
notifyLateUpdateStarted = resolve;
});
let holdDirectoryRefresh = false;
let releaseDirectoryRefresh: (() => void) | undefined;
let notifyDirectoryRefreshStarted: (() => void) | undefined;
const directoryRefreshGate = new Promise<void>((resolve) => {
releaseDirectoryRefresh = resolve;
});
const directoryRefreshStarted = new Promise<void>((resolve) => {
notifyDirectoryRefreshStarted = resolve;
});
await page.route("**/api/v1/me/organizations**", async (route) => {
if (holdDirectoryRefresh && route.request().method() === "GET") {
holdDirectoryRefresh = false;
const response = await route.fetch();
expect(response.status()).toBe(200);
notifyDirectoryRefreshStarted?.();
await directoryRefreshGate;
await route.fulfill({ response });
return;
}
await route.continue();
});
await page.route(`**/api/v1/organizations/${created.id}`, async (route) => {
if (route.request().method() === "GET") {
await route.continue();
return;
}
if (route.request().method() === "PATCH") {
const response = await route.fetch();
expect(response.status()).toBe(200);
notifyLateUpdateStarted?.();
await lateUpdateGate;
await route.fulfill({ response });
return;
}
await route.continue();
});
const lateUpdatedName = `${updatedName} Review`;
await page.getByLabel("Название компании").fill(lateUpdatedName);
await page.getByRole("button", { name: "Сохранить изменения" }).click();
await lateUpdateStarted;
await revokeCompanyMembership(created.id, userId, successorUserId);
holdDirectoryRefresh = true;
const deniedProfileResponse = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 404,
);
await page.getByRole("button", { name: "Обновить профиль" }).click();
await deniedProfileResponse;
await directoryRefreshStarted;
const accessLossNotice = page.getByText("Профиль компании недоступен", { exact: true });
await expect(accessLossNotice).toHaveCount(1);
await expect(accessLossNotice).toBeVisible();
const directoryRefreshResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/organizations" &&
response.status() === 200,
);
releaseDirectoryRefresh?.();
await directoryRefreshResponsePromise;
const lateUpdateResponsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PATCH" &&
new URL(response.url()).pathname === `/api/v1/organizations/${created.id}` &&
response.status() === 200,
);
releaseLateUpdate?.();
await lateUpdateResponsePromise;
await expect(page.getByText("Компаний пока нет", { exact: true })).toBeVisible();
await expect(accessLossNotice).toHaveCount(1);
await expect(accessLossNotice).toBeVisible();
await expect(page.getByText(companyDescription, { exact: true })).toHaveCount(0);
await expect(page.getByText(companyMailbox, { exact: true })).toHaveCount(0);
await expect(page.getByRole("article", { name: "Предпросмотр карточки компании" })).toHaveCount(
0,
);
});
});
+349
View File
@@ -0,0 +1,349 @@
import { expect, test, type Page } 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";
function e2eBaseUrl(): 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;
}
test.use({ trace: "off", screenshot: "off", video: "off" });
test.describe("candidate profile", () => {
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 login(page: Page, email: string): Promise<void> {
await page.goto("/candidate/profile");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: "Первые шаги" })).toBeVisible();
await page.goto("/candidate/profile");
await expect(page.getByRole("heading", { name: "Профиль" })).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toBeVisible();
}
async function registerCandidate(page: Page): Promise<{ email: string }> {
const suffix = crypto.randomUUID().slice(0, 8);
const email = `profile-${suffix}@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 message = await waitForVerification(email);
const verificationUrl = new URL("/verify-email", e2eBaseUrl());
verificationUrl.hash = `token=${verificationToken(message)}`;
await page.goto(verificationUrl.toString());
await expect(page.getByLabel("Пароль, выбранный при регистрации")).toBeVisible();
expect(await page.evaluate(() => window.location.hash)).toBe("");
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
await page.getByRole("button", { name: "Подтвердить почту" }).click();
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
await login(page, email);
return { email };
}
async function expectResponsiveKeyboardFlow(page: Page): Promise<void> {
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
await page.getByLabel("Имя и фамилия").focus();
await page.keyboard.press("Tab");
const focusedControlHasRing = await page.evaluate(() => {
const active = document.activeElement;
if (!(active instanceof HTMLElement) || !active.matches(":focus-visible")) return false;
const style = getComputedStyle(active);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(focusedControlHasRing, `visible focus at ${width}px`).toBe(true);
expect(hasHorizontalOverflow, `no horizontal overflow at ${width}px`).toBe(false);
}
}
async function saveProfile(page: Page, expectedStatus = 200): Promise<void> {
const responsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/profile",
);
await page.getByRole("button", { name: "Сохранить профиль" }).click();
expect((await responsePromise).status()).toBe(expectedStatus);
}
async function pauseProfileSave(page: Page) {
let intercepted = false;
let cleanupStarted = false;
let markForwarded: () => void = () => {};
let releaseRequest: () => void = () => {};
let routeTask: Promise<void> = Promise.resolve();
const forwarded = new Promise<void>((resolve) => {
markForwarded = resolve;
});
const gate = new Promise<void>((resolve) => {
releaseRequest = resolve;
});
const response = page.waitForResponse(
(item) =>
item.request().method() === "PUT" && new URL(item.url()).pathname === "/api/v1/me/profile",
);
void response.catch(() => undefined);
await page.route("**/api/v1/me/profile", (route) => {
if (route.request().method() !== "PUT" || intercepted) {
return route.continue();
}
intercepted = true;
routeTask = (async () => {
const result = await route.fetch();
markForwarded();
await gate;
try {
await route.fulfill({ response: result });
} catch (error: unknown) {
if (!cleanupStarted) throw error;
}
})();
return routeTask;
});
return {
forwarded,
response,
release: releaseRequest,
cleanup: async () => {
cleanupStarted = true;
releaseRequest();
await routeTask.catch(() => undefined);
await page.unroute("**/api/v1/me/profile");
},
};
}
test("saves manual profile data, reloads it, and preserves a stale draft through a version conflict", async ({
browser,
page,
}) => {
const suffix = crypto.randomUUID().slice(0, 8);
const name = `Тестовый профиль ${suffix}`;
const contactEmail = `contact-${suffix}@example.test`;
const { email } = await registerCandidate(page);
await page.setViewportSize({ width: 360, height: 900 });
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
await page.getByLabel("Имя и фамилия").fill(name);
await page.getByLabel("Контактный email").fill(contactEmail);
await page.getByLabel("Телефон").fill("+79990000000");
await page.getByLabel("Telegram").fill("@candidate_123");
await page.getByRole("button", { name: "Добавить место работы" }).click();
await page.getByRole("button", { name: "Добавить место работы" }).click();
await page.getByLabel("Компания").nth(0).fill("Первая компания");
await page.getByLabel("Компания").nth(1).fill("Вторая компания");
await page.getByLabel("Специализация").nth(0).selectOption("backend");
await page.getByLabel("Специализация").nth(1).selectOption("frontend");
await page.getByLabel("Начало работы").nth(0).fill("2024-01");
await page.getByLabel("Окончание работы").nth(0).fill("2024-12");
await page.getByLabel("Начало работы").nth(1).fill("2024-06");
await page.getByLabel("Окончание работы").nth(1).fill("2025-01");
await page.getByRole("checkbox", { name: /Подтверждаю, что места работы 1 и 2/ }).check();
await page.getByRole("button", { name: "Добавить специализацию" }).click();
await page.getByLabel("Специализация").nth(2).selectOption("backend");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByRole("button", { name: "Добавить навык" }).click();
await page.getByLabel("Навык 1", { exact: true }).fill("Go");
await page.getByRole("button", { name: "Добавить гибкий навык" }).click();
await page.getByLabel("Гибкий навык 1", { exact: true }).fill("Коммуникация");
await page.getByLabel("Желаемое место работы").fill("Москва");
await page.getByLabel("Готовность к переезду").selectOption("true");
await page.getByLabel("Минимальная зарплата, рублей в месяц").fill("150000");
await page.getByLabel("Сумма до или после налога").selectOption("gross");
const pausedSave = await pauseProfileSave(page);
try {
const saveButton = page.getByRole("button", { name: /Сохранить профиль|Сохраняем профиль/ });
await saveButton.click();
await pausedSave.forwarded;
await expect(page.getByLabel("Имя и фамилия")).toBeDisabled();
await expect(saveButton).toBeFocused();
await expect(saveButton).toHaveAttribute("aria-disabled", "true");
pausedSave.release();
expect((await pausedSave.response).status()).toBe(200);
await expect(page.getByLabel("Имя и фамилия")).toBeEnabled();
} finally {
pausedSave.release();
await pausedSave.cleanup();
}
await expect(
page.getByText("Профиль сохранен. Сервер подтвердил шаг аккаунта: Согласия."),
).toBeVisible();
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name);
await expect(
page.getByText(/Параллельная работа в местах 1 и 2 подтверждена ранее/),
).toBeVisible();
await page.screenshot({
path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/candidate-profile-mobile.png`,
animations: "disabled",
});
const profileNotPersistedInBrowserStorage = await page.evaluate((needle) => {
const serialized = [localStorage, sessionStorage]
.flatMap((storage) =>
Array.from({ length: storage.length }, (_, index) => {
const key = storage.key(index);
return key === null ? "" : `${key}:${storage.getItem(key) ?? ""}`;
}),
)
.join("\n");
return !serialized.includes(needle);
}, name);
expect(profileNotPersistedInBrowserStorage).toBe(true);
await page.reload();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name);
await expect(page.getByLabel("Контактный email")).toHaveValue(contactEmail);
await expect(page.getByLabel("Телефон")).toHaveValue("+79990000000");
await expect(page.getByLabel("Telegram")).toHaveValue("@candidate_123");
await expect(page.getByLabel("Навык 1", { exact: true })).toHaveValue("Go");
await expect(page.getByLabel("Гибкий навык 1", { exact: true })).toHaveValue("Коммуникация");
await expect(page.getByLabel("Минимальная зарплата, рублей в месяц")).toHaveValue("150000");
await expect(page.getByText("Сохраненный шаг аккаунта: Согласия.")).toBeVisible();
await expectResponsiveKeyboardFlow(page);
const secondContext = await browser.newContext({
baseURL: e2eBaseUrl(),
locale: "ru-RU",
});
try {
const secondPage = await secondContext.newPage();
await login(secondPage, email);
const secondVersionName = `Изменение во втором окне ${suffix}`;
await secondPage.getByLabel("Имя и фамилия").fill(secondVersionName);
await saveProfile(secondPage);
const staleName = `Черновик первого окна ${suffix}`;
await page.getByLabel("Имя и фамилия").fill(staleName);
await saveProfile(page, 412);
await expect(
page.getByRole("heading", { name: "Профиль обновлен в другом окне" }),
).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName);
const latestRead = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/profile" &&
response.status() === 200,
);
await page.getByRole("button", { name: "Заменить черновик актуальной версией" }).click();
await latestRead;
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(secondVersionName);
await page.getByLabel("Имя и фамилия").fill(staleName);
await saveProfile(page);
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName);
await expectResponsiveKeyboardFlow(page);
await page.reload();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName);
} finally {
await secondContext.close();
}
});
test("does not cache a pending save after the account changes", async ({ browser, page }) => {
const firstAccount = await registerCandidate(page);
const firstProfileName = `Первый профиль ${crypto.randomUUID().slice(0, 8)}`;
await page.getByLabel("Имя и фамилия").fill(firstProfileName);
const pausedSave = await pauseProfileSave(page);
try {
const saveButton = page.getByRole("button", { name: /Сохранить профиль|Сохраняем профиль/ });
await saveButton.click();
await pausedSave.forwarded;
await expect(page.getByLabel("Имя и фамилия")).toBeDisabled();
const secondContext = await browser.newContext({
baseURL: e2eBaseUrl(),
locale: "ru-RU",
});
let secondAccount: { email: string };
try {
const secondPage = await secondContext.newPage();
secondAccount = await registerCandidate(secondPage);
} finally {
await secondContext.close();
}
await page.evaluate(() => {
window.history.pushState({}, "", "/login");
window.dispatchEvent(new PopStateEvent("popstate"));
});
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(secondAccount.email);
await page.getByLabel("Пароль", { exact: true }).fill(password);
await page.getByRole("button", { name: "Войти" }).click();
await expect(page.getByRole("heading", { name: "Первые шаги" })).toBeVisible();
await page.getByRole("link", { name: "Профиль" }).click();
await expect(page.getByRole("heading", { name: "Профиль" })).toBeVisible();
await expect(page.getByLabel("Имя и фамилия")).toHaveValue("");
pausedSave.release();
expect((await pausedSave.response).status()).toBe(200);
await expect(page.getByLabel("Имя и фамилия")).toHaveValue("");
await expect(page.getByText(firstProfileName)).toHaveCount(0);
expect(firstAccount.email).not.toBe(secondAccount.email);
} finally {
pausedSave.release();
await pausedSave.cleanup();
}
});
});
+529
View File
@@ -0,0 +1,529 @@
import { expect, test, type Browser, type Page, type Route } from "@playwright/test";
type InboxMessage = {
id: string;
text?: string;
html?: string;
};
type InboxResponse = {
messages: InboxMessage[];
};
type QuestionnaireResponse = {
version: number;
updated_at?: string | null;
specializations: {
specialization: string;
self_assessed_grade: string;
task_languages: string[];
stack: string[];
experience: { commercial_months: number; academic_months: number } | null;
}[];
work_context: { work_formats: string[] } | null;
};
const questionnaireFixtureEnabled = process.env.E2E_QUESTIONNAIRE_FIXTURE === "1";
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 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<{ email: string }> {
const email = `questionnaire-${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 signIn(page, email);
return { email };
}
async function signIn(page: Page, email: string): Promise<void> {
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);
await page.goto("/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Анкета" })).toBeVisible();
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
}
async function checkResponsiveLayout(page: Page): Promise<void> {
for (const width of [360, 768, 1280]) {
await page.setViewportSize({ width, height: 900 });
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > window.innerWidth,
);
expect(hasHorizontalOverflow, `no horizontal overflow at ${width}px`).toBe(false);
if (width === 360) continue;
await page.getByLabel("Специализация", { exact: true }).focus();
await page.keyboard.press("Tab");
const hasVisibleFocus = await page.evaluate(() => {
const active = document.activeElement;
if (!(active instanceof HTMLElement) || !active.matches(":focus-visible")) return false;
const style = getComputedStyle(active);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(hasVisibleFocus, `visible keyboard focus at ${width}px`).toBe(true);
}
await page.setViewportSize({ width: 360, height: 900 });
}
async function tabToSaveButton(page: Page): Promise<void> {
const saveButton = page.getByRole("button", { name: "Сохранить анкету" });
await page.evaluate(() => {
if (document.activeElement instanceof HTMLElement) document.activeElement.blur();
});
let reached = false;
for (let index = 0; index < 50; index += 1) {
await page.keyboard.press("Tab");
if (await saveButton.evaluate((button) => document.activeElement === button)) {
reached = true;
break;
}
}
expect(reached, "keyboard can reach the questionnaire save action").toBe(true);
const hasVisibleFocus = await saveButton.evaluate((button) => {
if (!(button instanceof HTMLElement) || !button.matches(":focus-visible")) return false;
const style = getComputedStyle(button);
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
});
expect(hasVisibleFocus, "save action has a visible keyboard focus indicator").toBe(true);
}
async function saveFromKeyboard(page: Page, expectedStatus: number): Promise<void> {
const responsePromise = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await tabToSaveButton(page);
await page.keyboard.press("Enter");
expect((await responsePromise).status()).toBe(expectedStatus);
}
async function createSecondSession(browser: Browser, email: string): Promise<Page> {
const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
const page = await context.newPage();
await signIn(page, email);
return page;
}
async function navigateInApp(page: Page, path: string): Promise<void> {
await page.evaluate((target) => {
window.history.pushState(window.history.state, "", target);
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
}, path);
}
async function fulfillProblem(route: Route, status: number, code: string): Promise<void> {
await route.fulfill({
status,
headers: { "content-type": "application/problem+json" },
body: JSON.stringify({
type: `urn:lincodex:problem:${code}`,
title: code,
status,
code,
}),
});
}
test.describe("candidate questionnaire", () => {
test("saves real catalog answers, reloads them, and preserves a draft after 412", async ({
browser,
page,
}) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local published Backend bank and mail fixtures.",
);
const { email } = await registerVerifiedCandidate(page);
await page.setViewportSize({ width: 360, height: 900 });
const catalogResponse = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/specializations",
);
const questionnaireResponse = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.goto("/candidate/questionnaire");
expect((await catalogResponse).status()).toBe(200);
const initialResponse = await questionnaireResponse;
expect(initialResponse.status()).toBe(200);
const initial = (await initialResponse.json()) as QuestionnaireResponse;
expect(initial.version).toBe(0);
const specialization = page.getByLabel("Специализация", { exact: true });
await specialization.selectOption("ds_ml");
await expect(page.getByText("Проверка: в разработке")).toBeVisible();
await expect(
page.getByText("Эту специализацию можно сохранить. Начать проверку по ней пока нельзя."),
).toBeVisible();
await expect(page.getByRole("button", { name: /проверку/i })).toHaveCount(0);
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
await saveFromKeyboard(page, 200);
await expect(
page.getByText(/Анкета сохранена\. Сервер подтвердил шаг аккаунта:/),
).toBeVisible();
await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible();
await specialization.selectOption("backend");
await page.getByLabel("Моя оценка уровня").selectOption("junior");
await page.getByRole("checkbox", { name: "Go", exact: true }).check();
await page.getByLabel("Стек технологий").fill("Go");
await page.getByRole("button", { name: "Добавить технологию" }).click();
const backendSave = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
const backendSaveResponse = await backendSave;
expect(backendSaveResponse.status()).toBe(200);
const savedBackend = (await backendSaveResponse.json()) as QuestionnaireResponse;
expect(savedBackend.specializations).toEqual([
{
specialization: "backend",
self_assessed_grade: "junior",
task_languages: ["go"],
stack: ["Go"],
experience: null,
},
]);
await expect(page.getByText(/Анкета сохранена/)).toBeVisible();
await page.reload();
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("backend");
await expect(page.getByLabel("Моя оценка уровня")).toHaveValue("junior");
await expect(page.getByRole("checkbox", { name: "Go", exact: true })).toBeChecked();
await expect(page.getByLabel("Стек технологий")).toHaveValue("");
await expect(page.getByText(/Шаг аккаунта на сервере: Согласия\./)).toBeVisible();
await page.screenshot({
path: `${process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e"}/questionnaire-360.png`,
});
await checkResponsiveLayout(page);
const secondPage = await createSecondSession(browser, email);
try {
await secondPage.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await secondPage.getByLabel("Моя оценка уровня").selectOption("senior");
const concurrentSave = secondPage.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await secondPage.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await concurrentSave).status()).toBe(200);
await page.getByLabel("Удаленно").uncheck();
await page.getByLabel("В офисе").check();
const staleSave = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await staleSave).status()).toBe(412);
await expect(
page.getByRole("heading", { name: "Анкета изменилась в другом окне" }),
).toBeVisible();
await expect(page.getByLabel("Удаленно")).not.toBeChecked();
await expect(page.getByLabel("В офисе")).toBeChecked();
await expect(page.getByText(/Последняя прочитанная серверная версия:/)).toBeVisible();
const reapply = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page
.getByRole("button", { name: "Записать этот черновик поверх актуальной анкеты" })
.click();
expect((await reapply).status()).toBe(200);
await expect(page.getByText(/Анкета сохранена/)).toBeVisible();
await secondPage.reload();
await expect(secondPage.getByLabel("В офисе")).toBeChecked();
await expect(secondPage.getByLabel("Удаленно")).not.toBeChecked();
await checkResponsiveLayout(page);
} finally {
await secondPage.context().close();
}
});
test("blocks questionnaire reads after an API 401 with a cached session", async ({ page }) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local questionnaire and mail fixtures.",
);
await registerVerifiedCandidate(page);
await page.getByRole("link", { name: "Профиль" }).click();
await expect(page.getByRole("heading", { name: "Профиль" })).toBeVisible();
await page.route("**/api/v1/me/questionnaire", async (route) => {
if (route.request().method() === "GET") {
await fulfillProblem(route, 401, "unauthenticated");
return;
}
await route.continue();
});
const failedRead = page.waitForResponse(
(response) =>
response.request().method() === "GET" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("link", { name: "Анкета" }).click();
expect((await failedRead).status()).toBe(401);
await expect(page.getByText("Анкета недоступна", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toHaveCount(0);
await expect(page.getByLabel("Специализация", { exact: true })).toHaveCount(0);
});
test("clears the editor after a non-CSRF 403 response", async ({ page }) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local questionnaire and mail fixtures.",
);
await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
await page.route("**/api/v1/me/questionnaire", async (route) => {
if (route.request().method() === "PUT") {
await fulfillProblem(route, 403, "forbidden");
return;
}
await route.continue();
});
const saveResponse = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await saveResponse).status()).toBe(403);
await expect(page.getByText("Анкета недоступна", { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toHaveCount(0);
await expect(page.getByLabel("Специализация", { exact: true })).toHaveCount(0);
});
test("keeps a draft after a successful CSRF refresh and hides it when refresh fails", async ({
page,
}) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local questionnaire and mail fixtures.",
);
await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
let rejectSessionRefresh = false;
await page.route("**/api/v1/identity/sessions/current", async (route) => {
if (rejectSessionRefresh) {
await fulfillProblem(route, 401, "unauthenticated");
return;
}
await route.continue();
});
await page.route("**/api/v1/me/questionnaire", async (route) => {
if (route.request().method() === "PUT") {
await fulfillProblem(route, 403, "csrf_check_failed");
return;
}
await route.continue();
});
const firstSave = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await firstSave).status()).toBe(403);
await expect(
page.getByText("Проверка входа обновлена. Ответы остались в форме, повторите сохранение."),
).toBeVisible();
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("ds_ml");
rejectSessionRefresh = true;
const secondSave = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
await page.getByRole("button", { name: "Сохранить анкету" }).click();
expect((await secondSave).status()).toBe(403);
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toHaveCount(0);
});
test("ignores an old account save response after signing in to another account", async ({
browser,
page,
}) => {
test.skip(
!questionnaireFixtureEnabled || !mailFixtureEnabled,
"Requires the local questionnaire and mail fixtures.",
);
const secondContext = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
let secondEmail: string;
try {
const secondAccountPage = await secondContext.newPage();
({ email: secondEmail } = await registerVerifiedCandidate(secondAccountPage));
} finally {
await secondContext.close();
}
await registerVerifiedCandidate(page);
await page.getByLabel("Специализация", { exact: true }).selectOption("ds_ml");
await page.getByLabel("Моя оценка уровня").selectOption("senior");
await page.getByLabel("Удаленно").check();
let releaseOldResponse: () => void = () => undefined;
let markOldRequestHeld: () => void = () => undefined;
const oldResponseGate = new Promise<void>((resolve) => {
releaseOldResponse = resolve;
});
const oldRequestHeld = new Promise<void>((resolve) => {
markOldRequestHeld = resolve;
});
let held = false;
let cleanupStarted = false;
let requestForwarded = false;
await page.route("**/api/v1/me/questionnaire", (route) => {
if (route.request().method() === "PUT" && !held) {
held = true;
return (async () => {
const response = await route.fetch();
requestForwarded = true;
markOldRequestHeld();
await oldResponseGate;
try {
await route.fulfill({ response });
} catch (error: unknown) {
if (!cleanupStarted) throw error;
}
})();
}
return route.continue();
});
const oldSaveResponse = page.waitForResponse(
(response) =>
response.request().method() === "PUT" &&
new URL(response.url()).pathname === "/api/v1/me/questionnaire",
);
void oldSaveResponse.catch(() => undefined);
try {
await page.getByRole("button", { name: "Сохранить анкету" }).click();
await oldRequestHeld;
await navigateInApp(page, "/login");
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
await page.getByLabel("Электронная почта").fill(secondEmail);
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);
await navigateInApp(page, "/candidate/questionnaire");
await expect(page.getByRole("heading", { name: "Ответы кандидата" })).toBeVisible();
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("");
releaseOldResponse();
expect((await oldSaveResponse).status()).toBe(200);
await expect(page.getByLabel("Специализация", { exact: true })).toHaveValue("");
await expect(page.getByLabel("Моя оценка уровня")).toHaveValue("");
await expect(page.getByRole("button", { name: "Сохранить анкету" })).toBeEnabled();
await expect(page.getByRole("button", { name: "Сохраняем анкету..." })).toHaveCount(0);
} finally {
cleanupStarted = true;
releaseOldResponse();
if (requestForwarded) await oldSaveResponse.catch(() => undefined);
await page.unroute("**/api/v1/me/questionnaire");
}
});
});