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 { 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 { 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 { 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 { 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); } } // The profile is a form in steps. "Далее" checks the visible step and moves // the focus to the heading of the next one; the save is on the last step. async function nextStep(page: Page, heading: string): Promise { await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused(); } async function editStep(page: Page, step: string, heading: string): Promise { await page.getByRole("button", { name: `Изменить: ${step}` }).click(); await expect(page.getByRole("heading", { name: new RegExp(`\\. ${heading}$`) })).toBeFocused(); } async function openReview(page: Page): Promise { const save = page.getByRole("button", { name: /Сохранить профиль|Сохраняем профиль/ }); const jump = page.getByRole("button", { name: "К проверке и сохранению" }); if (await save.isVisible()) return; if (await jump.isVisible()) { await jump.click(); await expect(page.getByRole("heading", { name: /\. Проверка$/ })).toBeFocused(); return; } for (const heading of ["Роли", "Опыт", "Проекты", "Навыки", "Условия", "Проверка"]) { if (await save.isVisible()) break; await nextStep(page, heading); } await expect(save).toBeVisible(); } async function saveProfile(page: Page, expectedStatus = 200): Promise { await openReview(page); 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 = Promise.resolve(); const forwarded = new Promise((resolve) => { markForwarded = resolve; }); const gate = new Promise((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 projectTitle = `Платежный шлюз ${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 expect(page.getByText("Шаг 1 из 7", { exact: true })).toBeVisible(); await nextStep(page, "Роли"); await page.getByRole("button", { name: "Добавить специализацию" }).click(); await page.getByLabel("Специализация").selectOption("backend"); await page.getByLabel("Моя оценка уровня").selectOption("senior"); await nextStep(page, "Опыт"); await page.getByRole("button", { name: "Добавить место работы" }).click(); await page.getByRole("button", { name: "Добавить место работы" }).click(); const experienceSpecialization = page.getByLabel("Специализация").filter({ visible: true }); await page.getByLabel("Компания").nth(0).fill("Первая компания"); await page.getByLabel("Компания").nth(1).fill("Вторая компания"); await experienceSpecialization.nth(0).selectOption("backend"); await experienceSpecialization.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"); // The overlapping periods block the step until they are confirmed. await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect( page.getByRole("alert").filter({ hasText: "действительно шли параллельно" }), ).toBeFocused(); await page.getByRole("checkbox", { name: /Подтверждаю, что места работы 1 и 2/ }).check(); await nextStep(page, "Проекты"); await page.getByRole("button", { name: "Добавить проект" }).click(); await page.getByLabel("Название", { exact: true }).fill(projectTitle); await page.getByLabel("Что делает проект и что делали вы").fill("Проводки и сверки платежей."); const projectTags = page.getByLabel("Технологии проекта"); await projectTags.fill("Go"); await projectTags.press("Enter"); await projectTags.fill("PostgreSQL, Kafka"); await projectTags.press("Enter"); await expect(page.getByRole("button", { name: /Убрать технологию Kafka/ })).toBeVisible(); // A wrong repository address stops the step and names the field. await page.getByLabel("Репозиторий на GitHub, необязательно").fill("https://gitlab.com/a/b"); await page.getByRole("button", { name: "Далее", exact: true }).click(); await expect(page.getByRole("alert").filter({ hasText: "Проекты, проект 1" })).toBeFocused(); await expect(page.getByText(/Нужен адрес вида https:\/\/github\.com/).first()).toBeVisible(); await page.getByLabel("Репозиторий на GitHub, необязательно").fill(""); await nextStep(page, "Навыки"); 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 nextStep(page, "Условия"); await page.getByLabel("Желаемое место работы").fill("Москва"); await page.getByLabel("Готовность к переезду").selectOption("true"); await page.getByLabel("Минимальная зарплата, рублей в месяц").fill("150000"); await page.getByLabel("Сумма до или после налога").selectOption("gross"); await nextStep(page, "Проверка"); // Back keeps the entered data. await page.getByRole("button", { name: "Назад", exact: true }).click(); await expect(page.getByRole("heading", { name: /\. Условия$/ })).toBeFocused(); await expect(page.getByLabel("Желаемое место работы")).toHaveValue("Москва"); await nextStep(page, "Проверка"); 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 editStep(page, "опыт", "Опыт"); 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); // The saved project comes back with its tags. await openReview(page); await editStep(page, "проекты", "Проекты"); await expect(page.getByLabel("Название", { exact: true })).toHaveValue(projectTitle); await expect(page.getByLabel("Что делает проект и что делали вы")).toHaveValue( "Проводки и сверки платежей.", ); await expect(page.getByRole("button", { name: /Убрать технологию PostgreSQL/ })).toBeVisible(); await page.reload(); await expect(page.getByLabel("Имя и фамилия")).toHaveValue(name); 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 editStep(page, "контакты", "Контакты"); await page.getByLabel("Имя и фамилия").fill(staleName); await saveProfile(page); await expect(page.getByLabel("Имя и фамилия")).toHaveValue(staleName); await editStep(page, "контакты", "Контакты"); 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); await openReview(page); 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(); } }); });