1162 lines
53 KiB
TypeScript
1162 lines
53 KiB
TypeScript
import { expect, test, type Browser, type Locator, type Page, type Route } from "@playwright/test";
|
||
|
||
// Two groups share this file. The first runs against the real backend: five
|
||
// synthetic candidates publish the same card with declared, unconfirmed
|
||
// grades, and the owner of a fresh organization searches the real bank. The
|
||
// isolated stand has no confirmed category for several people at once (a card
|
||
// is shown only in a group of at least five identical cards), so the real
|
||
// group covers the unconfirmed group, the specializations of one candidate,
|
||
// the explanation from the server, the card read, and an empty result. The
|
||
// second group answers every API call from a small fake, so it checks the
|
||
// parts the stand cannot produce: the order of all three groups, a candidate
|
||
// confirmed in one specialization and not in another, a partial output, the
|
||
// quota refusal of a card read, and the other failure states.
|
||
//
|
||
// The real-bank test runs in its own Playwright project, before every other
|
||
// spec (frontend/playwright.config.ts). The unfiltered search returns at most
|
||
// ten entries per group, and for a bank search Fit and Coverage are equal for
|
||
// every unconfirmed entry, so the group is ordered by the internal candidate
|
||
// identifier. A candidate published by another spec earlier in the same stand
|
||
// would therefore push this test's candidates out of the group at random.
|
||
|
||
const mailFixtureEnabled = process.env.E2E_MAIL_FIXTURE === "1";
|
||
const companyFixtureEnabled = process.env.E2E_COMPANY_FIXTURE === "1";
|
||
const password = "correct horse battery staple 2026";
|
||
|
||
test.use({ trace: "off", screenshot: "off", video: "off" });
|
||
|
||
type ApiResult = { status: number; body: unknown };
|
||
type InboxMessage = { text?: string; html?: string };
|
||
|
||
type ServerCard = {
|
||
candidate_handle: string;
|
||
specialization: string;
|
||
confirmation_status: string;
|
||
declared_grade: string | null;
|
||
category: { specialization: string; grade: string } | null;
|
||
components: Record<string, number | null>;
|
||
unknown_flags: { component: string; reason: string }[];
|
||
};
|
||
type ServerResult = {
|
||
source: { kind: string };
|
||
groups: { main: ServerCard[]; near: ServerCard[]; unconfirmed: ServerCard[] };
|
||
truncated: boolean;
|
||
};
|
||
|
||
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;
|
||
}
|
||
|
||
function formatScore(value: number): string {
|
||
return value.toLocaleString("ru-RU", { minimumFractionDigits: 2, maximumFractionDigits: 6 });
|
||
}
|
||
|
||
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
|
||
for (const width of [360, 768, 1280]) {
|
||
await page.setViewportSize({ width, height: 900 });
|
||
const overflow = await page.evaluate(
|
||
() => document.documentElement.scrollWidth > window.innerWidth,
|
||
);
|
||
expect(overflow, `no horizontal overflow at ${width}px`).toBe(false);
|
||
}
|
||
}
|
||
|
||
async function hasVisibleFocusRing(element: Locator): Promise<boolean> {
|
||
return element.evaluate((node) => {
|
||
if (!(node instanceof HTMLElement) || !node.matches(":focus-visible")) return false;
|
||
const style = getComputedStyle(node);
|
||
return style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0;
|
||
});
|
||
}
|
||
|
||
// Moves focus with Tab only, so the check proves that a keyboard user reaches
|
||
// the control and sees where the focus is.
|
||
async function focusByTab(page: Page, target: Locator): Promise<void> {
|
||
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
|
||
for (let attempt = 0; attempt < 250; attempt += 1) {
|
||
await page.keyboard.press("Tab");
|
||
if (await target.evaluate((element) => element === document.activeElement)) {
|
||
expect(await hasVisibleFocusRing(target)).toBe(true);
|
||
return;
|
||
}
|
||
}
|
||
throw new Error("Keyboard navigation did not reach the requested control.");
|
||
}
|
||
|
||
async function captureReview(page: Page, name: string): Promise<void> {
|
||
const directory = process.env.E2E_ARTIFACTS_DIR ?? "test-results/e2e";
|
||
for (const width of [360, 1280]) {
|
||
await page.setViewportSize({ width, height: 1400 });
|
||
await page.screenshot({
|
||
path: `${directory}/${name}-${width}.png`,
|
||
animations: "disabled",
|
||
fullPage: true,
|
||
});
|
||
}
|
||
}
|
||
|
||
function groupSection(page: Page, name: string): Locator {
|
||
return page.getByRole("region", { name, exact: true });
|
||
}
|
||
|
||
function searchResponse(page: Page) {
|
||
return page.waitForResponse(
|
||
(response) =>
|
||
response.request().method() === "POST" &&
|
||
/^\/api\/v1\/organizations\/[0-9a-f-]+\/matches$/.test(new URL(response.url()).pathname),
|
||
);
|
||
}
|
||
|
||
async function groupHeadings(page: Page): Promise<string[]> {
|
||
return page.getByRole("heading", { level: 3 }).allInnerTexts();
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Real backend
|
||
// ---------------------------------------------------------------------------
|
||
|
||
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 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 { messages: InboxMessage[] }).messages;
|
||
}
|
||
|
||
async function verificationToken(email: string): Promise<string> {
|
||
const deadline = Date.now() + 20_000;
|
||
while (Date.now() < deadline) {
|
||
const message = (await readInbox(email)).at(-1);
|
||
if (message) {
|
||
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 registration message had no verification link.");
|
||
return token;
|
||
}
|
||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||
}
|
||
throw new Error("The local mailbox did not receive the verification message.");
|
||
}
|
||
|
||
// Registers, confirms, and signs in a synthetic account.
|
||
async function createAccount(page: Page, scenario: "candidate" | "employer"): Promise<void> {
|
||
const suffix = crypto.randomUUID().replaceAll("-", "").slice(0, 8);
|
||
const email =
|
||
scenario === "employer" ? `company-${suffix}@example.test` : `search-${suffix}@example.test`;
|
||
await page.goto("/register");
|
||
await page.getByLabel("Электронная почта").fill(email);
|
||
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
||
await page
|
||
.getByRole("radio", { name: scenario === "employer" ? /Работодатель/ : /Кандидат/ })
|
||
.check();
|
||
await page.getByRole("checkbox", { name: /принимаю его/ }).check();
|
||
await page.getByRole("button", { name: "Создать аккаунт" }).click();
|
||
await expect(page.getByRole("heading", { name: "Запрос принят" })).toBeVisible();
|
||
|
||
const verificationUrl = new URL("/verify-email", baseUrl());
|
||
verificationUrl.hash = `token=${await verificationToken(email)}`;
|
||
await page.goto(verificationUrl.toString());
|
||
await page.getByLabel("Пароль, выбранный при регистрации").fill(password);
|
||
await page.getByRole("button", { name: "Подтвердить почту" }).click();
|
||
await expect(page.getByText(/Почта подтверждена/)).toBeVisible();
|
||
|
||
await page.goto(scenario === "employer" ? "/employer/company" : "/candidate");
|
||
await expect(page.getByRole("heading", { name: "Вход" })).toBeVisible();
|
||
await page.getByLabel("Электронная почта").fill(email);
|
||
await page.getByLabel("Пароль", { exact: true }).fill(password);
|
||
const loginResponse = page.waitForResponse(
|
||
(response) =>
|
||
response.request().method() === "POST" &&
|
||
new URL(response.url()).pathname === "/api/v1/identity/sessions" &&
|
||
response.status() === 201,
|
||
);
|
||
await page.getByRole("button", { name: "Войти" }).click();
|
||
await loginResponse;
|
||
}
|
||
|
||
// Calls the API from the page, so the cookie and the origin are the browser's.
|
||
async function api(page: Page, method: string, path: string, body?: unknown): Promise<ApiResult> {
|
||
return page.evaluate(
|
||
async ({ method, path, body }) => {
|
||
const headers: Record<string, string> = {};
|
||
if (method !== "GET") {
|
||
const session = await fetch("/api/v1/identity/sessions/current", {
|
||
credentials: "include",
|
||
});
|
||
headers["X-CSRF-Token"] = ((await session.json()) as { csrf_token: string }).csrf_token;
|
||
headers["Idempotency-Key"] = crypto.randomUUID();
|
||
}
|
||
if (body !== undefined) headers["Content-Type"] = "application/json";
|
||
const response = await fetch(path, {
|
||
method,
|
||
headers,
|
||
credentials: "include",
|
||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||
});
|
||
return { status: response.status, body: await response.json().catch(() => null) };
|
||
},
|
||
{ method, path, body },
|
||
);
|
||
}
|
||
|
||
// A candidate with two declared specializations, no test, an active C2, and a
|
||
// published card that holds only the self-assessment. Five of them share one
|
||
// card, which is what the minimum group size of the card projection needs.
|
||
async function publishDeclaredCandidate(browser: Browser): Promise<void> {
|
||
const context = await browser.newContext({ baseURL: baseUrl(), locale: "ru-RU" });
|
||
try {
|
||
const page = await context.newPage();
|
||
await createAccount(page, "candidate");
|
||
const profile = await api(page, "PUT", "/api/v1/me/profile", {
|
||
expected_version: 0,
|
||
full_name: { value: "Тестовый кандидат", status: "confirmed" },
|
||
contacts: { email: null, phone: null, telegram: null },
|
||
stack: [],
|
||
roles: [
|
||
{ specialization: "backend", self_assessed_grade: "senior", status: "confirmed" },
|
||
{ specialization: "network_engineer", self_assessed_grade: "intern", status: "confirmed" },
|
||
],
|
||
experience: [],
|
||
soft_skills: [],
|
||
terms: { location: null, relocation: null, salary_minimum: null },
|
||
});
|
||
expect(profile.status).toBe(200);
|
||
const text = await api(page, "GET", "/api/v1/me/consent-texts/c2");
|
||
expect(text.status).toBe(200);
|
||
const granted = await api(page, "PUT", "/api/v1/me/consents/c2", {
|
||
text_version: (text.body as { text_version: string }).text_version,
|
||
accepted: true,
|
||
});
|
||
expect(granted.status).toBe(200);
|
||
const published = await api(page, "PUT", "/api/v1/me/privacy/publication", {
|
||
expected_version: 0,
|
||
state: "published",
|
||
fields: ["self_assessment"],
|
||
});
|
||
expect(published.status).toBe(200);
|
||
} finally {
|
||
await context.close();
|
||
}
|
||
}
|
||
|
||
test.describe("employer candidate search with the real backend", () => {
|
||
test.skip(
|
||
!mailFixtureEnabled || !companyFixtureEnabled,
|
||
"Requires the isolated mail and company fixtures.",
|
||
);
|
||
|
||
test("searches the real bank, explains the result from the server and keeps the filters", async ({
|
||
browser,
|
||
page,
|
||
}) => {
|
||
test.setTimeout(420_000);
|
||
for (let index = 0; index < 5; index += 1) await publishDeclaredCandidate(browser);
|
||
|
||
await createAccount(page, "employer");
|
||
const organization = await api(page, "POST", "/api/v1/organizations", {
|
||
name: `Search team ${crypto.randomUUID().slice(0, 8)}`,
|
||
});
|
||
expect(organization.status).toBe(201);
|
||
const organizationId = (organization.body as { id: string }).id;
|
||
|
||
const matchRequests: string[] = [];
|
||
const cardRequests: string[] = [];
|
||
page.on("request", (request) => {
|
||
const { pathname } = new URL(request.url());
|
||
if (request.method() === "POST" && pathname.endsWith("/matches")) {
|
||
matchRequests.push(request.postData() ?? "");
|
||
}
|
||
if (pathname.includes("/candidate-cards/")) cardRequests.push(pathname);
|
||
});
|
||
|
||
await page.goto(`/employer/candidates?organization_id=${organizationId}`);
|
||
await expect(page.getByRole("heading", { level: 1, name: "Кандидаты" })).toBeVisible();
|
||
await expect(page.getByRole("radio", { name: "По всем профилям" })).toBeChecked();
|
||
// The quota is explained before the search, and nothing runs by itself.
|
||
await expect(page.getByText("Поиск расходует квоту просмотров карточек")).toBeVisible();
|
||
await expect(page.getByText("Поиск еще не запускался")).toBeVisible();
|
||
expect(matchRequests).toEqual([]);
|
||
|
||
// The declared grade filter isolates the five synthetic candidates.
|
||
await page.getByLabel("Заявленный кандидатом грейд").selectOption("senior");
|
||
const firstSearch = searchResponse(page);
|
||
await focusByTab(page, page.getByRole("button", { name: "Найти кандидатов" }));
|
||
await page.keyboard.press("Enter");
|
||
const first = await firstSearch;
|
||
expect(first.status()).toBe(200);
|
||
expect(JSON.parse(matchRequests[0] ?? "")).toEqual({ filters: { declared_grade: "senior" } });
|
||
const firstBody = (await first.json()) as ServerResult;
|
||
expect(firstBody.groups.main).toHaveLength(0);
|
||
expect(firstBody.groups.near).toHaveLength(0);
|
||
expect(firstBody.groups.unconfirmed).toHaveLength(5);
|
||
expect(firstBody.truncated).toBe(false);
|
||
|
||
await expect(page.getByRole("heading", { level: 2, name: "Результат поиска" })).toBeFocused();
|
||
expect(await groupHeadings(page)).toEqual([
|
||
"Подтвержденные",
|
||
"Близкие варианты",
|
||
"Грейд не подтвержден",
|
||
]);
|
||
await expect(groupSection(page, "Подтвержденные").getByText("Записей: 0")).toBeVisible();
|
||
await expect(groupSection(page, "Близкие варианты").getByText("Записей: 0")).toBeVisible();
|
||
await expect(groupSection(page, "Грейд не подтвержден").getByText("Записей: 5")).toBeVisible();
|
||
await expect(
|
||
page.getByText("Заявленный грейд (не подтверждение): Senior", { exact: true }),
|
||
).toBeVisible();
|
||
|
||
const unconfirmed = groupSection(page, "Грейд не подтвержден").getByRole("article");
|
||
await expect(unconfirmed).toHaveCount(5);
|
||
await expect(unconfirmed.first()).toContainText("Backend");
|
||
await expect(unconfirmed.first()).toContainText("Грейд не подтвержден");
|
||
await expect(unconfirmed.first()).toContainText("Senior");
|
||
// Unconfirmed profiles can be invited; the link carries the organization alias.
|
||
const invitations = groupSection(page, "Грейд не подтвержден").getByRole("link", {
|
||
name: /^Пригласить/,
|
||
});
|
||
await expect(invitations).toHaveCount(5);
|
||
const hrefs = await invitations.evaluateAll((links) =>
|
||
links.map((link) => link.getAttribute("href") ?? ""),
|
||
);
|
||
const sentHandles = firstBody.groups.unconfirmed.map((card) => card.candidate_handle).sort();
|
||
const linkedHandles = hrefs
|
||
.map((href) => new URL(href, "http://x").searchParams.get("candidate_handle") ?? "")
|
||
.sort();
|
||
expect(linkedHandles).toEqual(sentHandles);
|
||
for (const href of hrefs) {
|
||
expect(new URL(href, "http://x").searchParams.get("organization_id")).toBe(organizationId);
|
||
}
|
||
// No contact, no account identifier, no failed attempt anywhere in the result.
|
||
const resultText = await page.locator("main").innerText();
|
||
expect(resultText).not.toMatch(/@|\+\d{6}|провал|неудач/i);
|
||
|
||
// The explanation compares with the response of the search.
|
||
const firstCard = unconfirmed.first();
|
||
const expectedCard = firstBody.groups.unconfirmed[0];
|
||
if (!expectedCard) throw new Error("The search returned no unconfirmed entry.");
|
||
const toggle = firstCard.getByRole("button", { name: /объяснение/ });
|
||
await focusByTab(page, toggle);
|
||
await expect(toggle).toHaveAttribute("aria-expanded", "false");
|
||
await page.keyboard.press("Enter");
|
||
await expect(toggle).toHaveAttribute("aria-expanded", "true");
|
||
const explanation = firstCard.getByRole("region", { name: "Объяснение позиции" });
|
||
await expect(explanation).toBeVisible();
|
||
await expect(explanation.locator('[data-component="coverage"]')).toHaveText(
|
||
formatScore(expectedCard.components.coverage ?? Number.NaN),
|
||
);
|
||
await expect(explanation.locator('[data-component="fit"]')).toHaveText(
|
||
formatScore(expectedCard.components.fit ?? Number.NaN),
|
||
);
|
||
// An unconfirmed entry has no percentile, no category and no rank score.
|
||
await expect(explanation.locator('[data-component="percentile"]')).toHaveCount(0);
|
||
await expect(explanation.locator('[data-component="rank"]')).toHaveCount(0);
|
||
await expect(explanation).toContainText("Результат проверки");
|
||
await expect(explanation).toContainText("нет подтвержденного результата");
|
||
expect(expectedCard.unknown_flags).toContainEqual({
|
||
component: "assessment",
|
||
reason: "no_confirmation_for_specialization",
|
||
});
|
||
|
||
// The full card is read only when it is opened.
|
||
expect(cardRequests).toEqual([]);
|
||
const cardRead = page.waitForResponse(
|
||
(response) =>
|
||
response.request().method() === "GET" &&
|
||
new URL(response.url()).pathname ===
|
||
`/api/v1/organizations/${organizationId}/candidate-cards/${expectedCard.candidate_handle}`,
|
||
);
|
||
await firstCard.getByRole("button", { name: /Открыть карточку/ }).click();
|
||
expect((await cardRead).status()).toBe(200);
|
||
const cardPanel = firstCard.getByRole("region", { name: "Карточка кандидата" });
|
||
await expect(cardPanel).toBeVisible();
|
||
await expect(cardPanel.getByText("Грейд не подтвержден").first()).toBeVisible();
|
||
await expect(cardPanel.getByText("Подтвержденных категорий нет.")).toHaveCount(0);
|
||
await expect(cardPanel.getByText("Нет значения в карточке").first()).toBeVisible();
|
||
// A card without categories has no evidence section to read.
|
||
expect(cardRequests.filter((path) => path.endsWith("/evidence"))).toEqual([]);
|
||
expect(await cardPanel.innerText()).not.toMatch(/@|\+\d{6}/);
|
||
|
||
// A search without filters shows both specializations of one candidate apart.
|
||
await page.getByRole("button", { name: "Сбросить фильтры" }).click();
|
||
await expect(page.getByText("Условия поиска изменены")).toBeVisible();
|
||
const secondSearch = searchResponse(page);
|
||
await page.getByRole("button", { name: "Найти кандидатов" }).click();
|
||
const second = await secondSearch;
|
||
const secondBody = (await second.json()) as ServerResult;
|
||
expect(JSON.parse(matchRequests[1] ?? "")).toEqual({ filters: {} });
|
||
// The five candidates give exactly ten unconfirmed entries, the group limit.
|
||
// A truncated group means that another candidate shares the bank.
|
||
expect(secondBody.truncated, "the bank holds only the candidates of this test").toBe(false);
|
||
const sharedHandle = secondBody.groups.unconfirmed
|
||
.filter((card) => card.specialization === "backend" && card.declared_grade === "senior")
|
||
.map((card) => card.candidate_handle)
|
||
.find((handle) =>
|
||
secondBody.groups.unconfirmed.some(
|
||
(card) => card.candidate_handle === handle && card.specialization === "network_engineer",
|
||
),
|
||
);
|
||
expect(sharedHandle, "one candidate has Backend and Networks entries").toBeTruthy();
|
||
await expect(page.getByText("Условия поиска изменены")).toHaveCount(0);
|
||
|
||
const switcher = page.getByRole("group", { name: "Представление по специализациям" });
|
||
await expect(switcher).toBeVisible();
|
||
await switcher.getByRole("radio", { name: "Сетевое администрирование" }).check();
|
||
const networkCards = page.getByRole("article");
|
||
const networkCount = secondBody.groups.unconfirmed.filter(
|
||
(card) => card.specialization === "network_engineer",
|
||
).length;
|
||
await expect(networkCards).toHaveCount(networkCount);
|
||
for (const heading of await networkCards.getByRole("heading", { level: 4 }).allInnerTexts()) {
|
||
expect(heading).toBe("Сетевое администрирование");
|
||
}
|
||
await expect(networkCards.first()).toContainText("Грейд не подтвержден");
|
||
await expect(networkCards.first()).toContainText("Стажер");
|
||
await switcher.getByRole("radio", { name: "Backend" }).check();
|
||
const backendCount = [
|
||
...secondBody.groups.main,
|
||
...secondBody.groups.near,
|
||
...secondBody.groups.unconfirmed,
|
||
].filter((card) => card.specialization === "backend").length;
|
||
await expect(page.getByRole("article")).toHaveCount(backendCount);
|
||
await expect(
|
||
page.getByRole("link", { name: /^Пригласить кандидата .*Backend$/ }).first(),
|
||
).toBeVisible();
|
||
|
||
// An impossible mandatory filter gives an explained empty result and stays on.
|
||
await page.getByLabel("Подтвержденный грейд").selectOption("senior");
|
||
const emptySearch = searchResponse(page);
|
||
await page.getByRole("button", { name: "Найти кандидатов" }).click();
|
||
const emptyBody = (await (await emptySearch).json()) as ServerResult;
|
||
expect(JSON.parse(matchRequests[2] ?? "")).toEqual({ filters: { confirmed_grade: "senior" } });
|
||
expect(emptyBody.groups.main).toHaveLength(0);
|
||
expect(emptyBody.groups.unconfirmed).toHaveLength(0);
|
||
await expect(page.getByText("По этим условиям никого не нашли")).toBeVisible();
|
||
await expect(page.getByText("поиск не ослабляет их сам")).toBeVisible();
|
||
await expect(
|
||
page.getByText("Подтвержденный грейд: Senior", { exact: true }).first(),
|
||
).toBeVisible();
|
||
await expect(page.getByLabel("Подтвержденный грейд")).toHaveValue("senior");
|
||
expect(matchRequests).toHaveLength(3);
|
||
|
||
// A reload does not repeat the search by itself.
|
||
await page.reload();
|
||
await expect(page.getByText("Поиск еще не запускался")).toBeVisible();
|
||
expect(matchRequests).toHaveLength(3);
|
||
|
||
// Cards and the invitation link stay reachable at 360 px.
|
||
await page.setViewportSize({ width: 360, height: 800 });
|
||
await page.getByLabel("Заявленный кандидатом грейд").selectOption("senior");
|
||
const mobileSearch = searchResponse(page);
|
||
await page.getByRole("button", { name: "Найти кандидатов" }).click();
|
||
await mobileSearch;
|
||
const mobileLink = page.getByRole("link", { name: /^Пригласить/ }).first();
|
||
await focusByTab(page, mobileLink);
|
||
await expect(mobileLink).toBeInViewport();
|
||
await expectNoHorizontalOverflow(page);
|
||
await captureReview(page, "match-search-real");
|
||
});
|
||
});
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Stubbed API
|
||
// ---------------------------------------------------------------------------
|
||
|
||
const accountId = "01928f7a-0000-7000-8000-000000000001";
|
||
const orgId = "01928f7a-0000-7000-8000-00000000a001";
|
||
const needId = "01928f7a-0000-7000-8000-00000000d001";
|
||
const handleA = `cv1_${"A".repeat(43)}`;
|
||
const handleB = `cv1_${"B".repeat(43)}`;
|
||
const handleC = `cv1_${"C".repeat(43)}`;
|
||
|
||
const bankFilters = {
|
||
specialization: null,
|
||
confirmed_grade: null,
|
||
confirmed_category: null,
|
||
confirmation_status: null,
|
||
declared_grade: null,
|
||
stack: null,
|
||
conditions: null,
|
||
};
|
||
|
||
const noContext = {
|
||
stack: null,
|
||
experience_band: null,
|
||
work_formats: null,
|
||
salary_compatibility: null,
|
||
};
|
||
|
||
const semanticEvidence = [
|
||
{
|
||
requirement_kind: "task",
|
||
requirement_text: "Разработать сервис сверки платежей",
|
||
item_kind: "project",
|
||
project_title: "Платежный шлюз",
|
||
repository_verified: true,
|
||
similarity: "high",
|
||
},
|
||
{
|
||
requirement_kind: "required_skill",
|
||
requirement_text: "Проектирование схем PostgreSQL",
|
||
item_kind: "stack",
|
||
project_title: null,
|
||
repository_verified: false,
|
||
similarity: "medium",
|
||
},
|
||
];
|
||
|
||
function confirmedEntry(handle: string, grade: string, coverage: number, overrides = {}) {
|
||
return {
|
||
candidate_handle: handle,
|
||
specialization: "backend",
|
||
confirmation_status: "confirmed",
|
||
declared_grade: "senior",
|
||
category: { specialization: "backend", grade, basis: "synthetic_demo" },
|
||
strength: "strong",
|
||
public_context: {
|
||
stack: ["go", "postgresql"],
|
||
experience_band: "3_6",
|
||
work_formats: ["remote"],
|
||
salary_compatibility: "compatible",
|
||
},
|
||
evidence_summary: [
|
||
{ code: "confirmed_category", state: "supports" },
|
||
{ code: "required_skill_evidence", state: coverage < 0.25 ? "partial" : "supports" },
|
||
{ code: "desired_skill_evidence", state: "declared_only" },
|
||
],
|
||
semantic_evidence: [],
|
||
components: {
|
||
fit: 0.7125,
|
||
coverage,
|
||
domain: 0.5,
|
||
semantics: 0.5,
|
||
percentile: null,
|
||
competition: 0,
|
||
freshness: 0.5,
|
||
responsiveness: 0.5,
|
||
rank_score: 0.61,
|
||
},
|
||
unknown_flags: [
|
||
{ component: "semantics", reason: "ml_unavailable" },
|
||
{ component: "percentile", reason: "cohort_below_30" },
|
||
{ component: "freshness", reason: "no_freshness_history" },
|
||
{ component: "responsiveness", reason: "no_response_history" },
|
||
{ component: "domain", reason: "need_field_unconfirmed" },
|
||
],
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
function unconfirmedEntry(handle: string, specialization: string, declared: string | null) {
|
||
return {
|
||
candidate_handle: handle,
|
||
specialization,
|
||
confirmation_status: "unconfirmed",
|
||
declared_grade: declared,
|
||
category: null,
|
||
strength: null,
|
||
public_context: noContext,
|
||
evidence_summary: [
|
||
{ code: "declared_grade", state: "declared_only" },
|
||
{ code: "required_skill_evidence", state: "gap" },
|
||
],
|
||
semantic_evidence: [],
|
||
components: { fit: 0.51, coverage: 0.38 },
|
||
unknown_flags: [
|
||
{ component: "assessment", reason: "no_confirmation_for_specialization" },
|
||
{ component: "experience_band", reason: "not_in_public_card" },
|
||
],
|
||
};
|
||
}
|
||
|
||
function threeGroups(overrides: Record<string, unknown> = {}) {
|
||
return {
|
||
source: { kind: "bank", filters: bankFilters },
|
||
groups: {
|
||
main: [confirmedEntry(handleA, "middle", 0.853333)],
|
||
near: [confirmedEntry(handleB, "junior", 0.18, { declared_grade: null })],
|
||
unconfirmed: [
|
||
unconfirmedEntry(handleA, "network_engineer", "junior"),
|
||
unconfirmedEntry(handleC, "backend", null),
|
||
],
|
||
},
|
||
truncated: false,
|
||
...overrides,
|
||
};
|
||
}
|
||
|
||
function emptyGroups(overrides: Record<string, unknown> = {}) {
|
||
return threeGroups({ groups: { main: [], near: [], unconfirmed: [] }, ...overrides });
|
||
}
|
||
|
||
// The server repeats the filters of a bank search in a normalized form, so the
|
||
// stub does the same instead of echoing whatever the canned answer holds.
|
||
function echoBankFilters(response: unknown, body: Record<string, unknown>): unknown {
|
||
const result = response as { source: { kind: string; filters?: unknown } };
|
||
if (result.source.kind !== "bank") return response;
|
||
const sent = (body.filters ?? {}) as Record<string, unknown>;
|
||
const conditions = sent.conditions as Record<string, unknown> | undefined;
|
||
return {
|
||
...result,
|
||
source: {
|
||
kind: "bank",
|
||
filters: {
|
||
...bankFilters,
|
||
...sent,
|
||
conditions: conditions
|
||
? {
|
||
work_formats: conditions.work_formats ?? null,
|
||
salary_compatibility: conditions.salary_compatibility ?? null,
|
||
}
|
||
: null,
|
||
},
|
||
},
|
||
};
|
||
}
|
||
|
||
type FakeOptions = {
|
||
role?: "owner" | "recruiter";
|
||
scenario?: "employer" | "candidate";
|
||
searchStatus?: number;
|
||
/** One response per search call; the last one repeats. */
|
||
searches?: unknown[];
|
||
cardStatus?: number;
|
||
cardRetryAfter?: string;
|
||
card?: unknown;
|
||
evidence?: unknown;
|
||
needs?: { id: string; title: string }[];
|
||
requirementsVersion?: number;
|
||
};
|
||
|
||
type FakeCalls = { searches: Record<string, unknown>[]; paths: string[] };
|
||
|
||
function problemBody(status: number, code: string): string {
|
||
return JSON.stringify({ type: `urn:lincodex:problem:${code}`, title: code, status, code });
|
||
}
|
||
|
||
async function installFakeApi(page: Page, options: FakeOptions = {}): Promise<FakeCalls> {
|
||
const calls: FakeCalls = { searches: [], paths: [] };
|
||
await page.route("**/api/v1/**", async (route: Route) => {
|
||
const request = route.request();
|
||
const { pathname } = new URL(request.url());
|
||
const method = request.method();
|
||
calls.paths.push(`${method} ${pathname}`);
|
||
const json = (status: number, body: unknown) =>
|
||
route.fulfill({ status, contentType: "application/json", body: JSON.stringify(body) });
|
||
const problem = (status: number, code: string, headers: Record<string, string> = {}) =>
|
||
route.fulfill({
|
||
status,
|
||
contentType: "application/problem+json",
|
||
headers,
|
||
body: problemBody(status, code),
|
||
});
|
||
|
||
if (method === "GET" && pathname === "/api/v1/identity/sessions/current") {
|
||
return json(200, {
|
||
account: {
|
||
id: accountId,
|
||
email: "owner@example.test",
|
||
email_verified: true,
|
||
scenario: options.scenario ?? "employer",
|
||
onboarding_step: "employer_company",
|
||
created_at: "2026-10-07T12:00:00Z",
|
||
},
|
||
csrf_token: "A".repeat(43),
|
||
});
|
||
}
|
||
if (method === "GET" && pathname === "/api/v1/me/organizations") {
|
||
return json(200, {
|
||
items: [
|
||
{
|
||
organization: { id: orgId, name: "Компания А", verification_level: "e0" },
|
||
membership: {
|
||
organization_id: orgId,
|
||
role: options.role ?? "owner",
|
||
state: "active",
|
||
joined_at: "2026-10-01T10:00:00Z",
|
||
},
|
||
},
|
||
],
|
||
page: { has_more: false, next_cursor: null },
|
||
});
|
||
}
|
||
if (method === "GET" && pathname === `/api/v1/organizations/${orgId}/needs`) {
|
||
return json(200, {
|
||
items: (options.needs ?? []).map((need) => ({
|
||
...need,
|
||
vacancy_id: null,
|
||
version: 4,
|
||
specialization: { status: "confirmed", value: "backend" },
|
||
grade: { status: "unknown", value: null },
|
||
readiness: { status: "complete", missing_fields: [] },
|
||
created_at: "2026-10-01T10:00:00Z",
|
||
updated_at: "2026-10-02T10:00:00Z",
|
||
})),
|
||
page: { has_more: false, next_cursor: null },
|
||
});
|
||
}
|
||
const needMatch = /^\/api\/v1\/organizations\/[0-9a-f-]+\/needs\/([0-9a-f-]+)$/.exec(pathname);
|
||
if (method === "GET" && needMatch) {
|
||
const need = (options.needs ?? []).find((item) => item.id === needMatch[1]);
|
||
if (!need) return problem(404, "not_found");
|
||
return json(200, {
|
||
...need,
|
||
version: 4,
|
||
requirements_version: options.requirementsVersion ?? 3,
|
||
});
|
||
}
|
||
if (method === "POST" && pathname === `/api/v1/organizations/${orgId}/matches`) {
|
||
calls.searches.push(JSON.parse(request.postData() ?? "{}") as Record<string, unknown>);
|
||
if (options.searchStatus && options.searchStatus >= 400) {
|
||
return problem(
|
||
options.searchStatus,
|
||
options.searchStatus === 403 ? "forbidden" : "internal_error",
|
||
);
|
||
}
|
||
const responses = options.searches ?? [threeGroups()];
|
||
const index = Math.min(calls.searches.length - 1, responses.length - 1);
|
||
return json(200, echoBankFilters(responses[index], calls.searches.at(-1) ?? {}));
|
||
}
|
||
const cardMatch =
|
||
/^\/api\/v1\/organizations\/[0-9a-f-]+\/candidate-cards\/(cv1_[A-Za-z0-9_-]+)$/.exec(
|
||
pathname,
|
||
);
|
||
if (method === "GET" && cardMatch) {
|
||
if (options.cardStatus && options.cardStatus >= 400) {
|
||
return problem(
|
||
options.cardStatus,
|
||
options.cardStatus === 429 ? "rate_limited" : "not_found",
|
||
options.cardRetryAfter ? { "Retry-After": options.cardRetryAfter } : {},
|
||
);
|
||
}
|
||
return json(
|
||
200,
|
||
options.card ?? {
|
||
pseudonym: cardMatch[1],
|
||
categories: [
|
||
{
|
||
specialization: "backend",
|
||
grade: "middle",
|
||
strength: "strong",
|
||
basis: "synthetic_demo",
|
||
},
|
||
],
|
||
stack: ["go"],
|
||
self_assessment: [
|
||
{
|
||
specialization: "backend",
|
||
confirmation_status: "confirmed",
|
||
declared_grade: "senior",
|
||
},
|
||
{
|
||
specialization: "network_engineer",
|
||
confirmation_status: "unconfirmed",
|
||
declared_grade: "junior",
|
||
},
|
||
],
|
||
experience_band: "3_6",
|
||
work_formats: null,
|
||
salary_compatibility: "compatible",
|
||
projects: null,
|
||
},
|
||
);
|
||
}
|
||
if (method === "GET" && /\/candidate-cards\/cv1_[A-Za-z0-9_-]+\/evidence$/.test(pathname)) {
|
||
return json(
|
||
200,
|
||
options.evidence ?? {
|
||
items: [
|
||
{
|
||
skill: "backend",
|
||
grade: "middle",
|
||
trust: 1,
|
||
basis: "synthetic_demo",
|
||
calibration_status: "uncalibrated",
|
||
observed_year: 2026,
|
||
},
|
||
],
|
||
},
|
||
);
|
||
}
|
||
return problem(404, "not_found");
|
||
});
|
||
return calls;
|
||
}
|
||
|
||
async function openSearch(page: Page, query = ""): Promise<void> {
|
||
await page.goto(`/employer/candidates?organization_id=${orgId}${query}`);
|
||
await expect(page.getByRole("button", { name: "Найти кандидатов" })).toBeVisible();
|
||
}
|
||
|
||
async function runSearch(page: Page): Promise<void> {
|
||
const response = searchResponse(page);
|
||
await page.getByRole("button", { name: "Найти кандидатов" }).click();
|
||
await response;
|
||
}
|
||
|
||
test.describe("employer candidate search with a stubbed API", () => {
|
||
test("shows the three groups in order and one candidate under two specializations", async ({
|
||
page,
|
||
}) => {
|
||
const calls = await installFakeApi(page);
|
||
await openSearch(page);
|
||
// The page never searches by itself.
|
||
await expect(page.getByText("Поиск еще не запускался")).toBeVisible();
|
||
expect(calls.searches).toEqual([]);
|
||
|
||
await runSearch(page);
|
||
expect(calls.searches).toEqual([{ filters: {} }]);
|
||
expect(await groupHeadings(page)).toEqual([
|
||
"Подтвержденные",
|
||
"Близкие варианты",
|
||
"Грейд не подтвержден",
|
||
]);
|
||
// The cards come in group order and each group keeps the server order.
|
||
const order = await page.locator("[data-group] article h4").allInnerTexts();
|
||
expect(order).toEqual(["Backend", "Backend", "Сетевое администрирование", "Backend"]);
|
||
await expect(groupSection(page, "Подтвержденные").getByRole("article")).toHaveCount(1);
|
||
await expect(groupSection(page, "Близкие варианты").getByRole("article")).toHaveCount(1);
|
||
await expect(groupSection(page, "Грейд не подтвержден").getByRole("article")).toHaveCount(2);
|
||
|
||
// The confirmed and the declared grade have separate lines.
|
||
const confirmed = groupSection(page, "Подтвержденные").getByRole("article");
|
||
await expect(confirmed).toContainText("Грейд подтвержден: Middle");
|
||
await expect(confirmed).toContainText("Backend, Middle. Сильное подтверждение");
|
||
await expect(confirmed).toContainText("Заявленный кандидатом грейд");
|
||
await expect(confirmed).toContainText("Senior");
|
||
|
||
// One handle is confirmed in Backend and not confirmed in Networks.
|
||
const switcher = page.getByRole("group", { name: "Представление по специализациям" });
|
||
await switcher.getByRole("radio", { name: "Сетевое администрирование" }).check();
|
||
const networks = page.getByRole("article");
|
||
await expect(networks).toHaveCount(1);
|
||
await expect(networks).toContainText("Грейд не подтвержден");
|
||
await expect(networks).toContainText("Junior");
|
||
await expect(networks).not.toContainText("Грейд подтвержден:");
|
||
await expect(
|
||
groupSection(page, "Подтвержденные").getByText("В этой группе записей нет."),
|
||
).toBeVisible();
|
||
|
||
await switcher.getByRole("radio", { name: "Backend" }).check();
|
||
await expect(page.getByRole("article")).toHaveCount(3);
|
||
await expect(groupSection(page, "Подтвержденные").getByRole("article")).toContainText(
|
||
"Грейд подтвержден: Middle",
|
||
);
|
||
|
||
await captureReview(page, "match-search-three-groups");
|
||
});
|
||
|
||
test("invites an unconfirmed profile and carries the alias to the invitation form", async ({
|
||
page,
|
||
}) => {
|
||
await installFakeApi(page);
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
await page
|
||
.getByRole("group", { name: "Представление по специализациям" })
|
||
.getByRole("radio", { name: "Сетевое администрирование" })
|
||
.check();
|
||
const invite = page.getByRole("link", { name: /^Пригласить/ });
|
||
await expect(invite).toBeVisible();
|
||
await invite.click();
|
||
await expect(
|
||
page.getByRole("heading", { level: 1, name: "Приглашение кандидату" }),
|
||
).toBeVisible();
|
||
const url = new URL(page.url());
|
||
expect(url.pathname).toBe("/employer/invitations/new");
|
||
expect(url.searchParams.get("organization_id")).toBe(orgId);
|
||
expect(url.searchParams.get("candidate_handle")).toBe(handleA);
|
||
expect(url.searchParams.get("specialization")).toBe("network_engineer");
|
||
});
|
||
|
||
test("explains every component with the values and reasons of the server", async ({ page }) => {
|
||
await installFakeApi(page);
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
const confirmed = groupSection(page, "Подтвержденные").getByRole("article");
|
||
const toggle = confirmed.getByRole("button", { name: /объяснение/ });
|
||
await expect(confirmed.getByText("Как получена позиция")).toHaveCount(0);
|
||
await toggle.click();
|
||
await expect(toggle).toHaveAttribute("aria-expanded", "true");
|
||
const explanation = confirmed.getByRole("region", { name: "Объяснение позиции" });
|
||
await expect(explanation.locator('[data-component="coverage"]')).toHaveText("0,853333");
|
||
await expect(explanation.locator('[data-component="fit"]')).toHaveText("0,7125");
|
||
await expect(explanation.locator('[data-component="rank"]')).toHaveText("0,61");
|
||
// Neutral values are labelled, and the missing percentile is not invented.
|
||
const semantics = explanation.locator('[data-component="semantics"]');
|
||
await expect(semantics).toContainText("0,50");
|
||
await expect(semantics).toContainText("Нейтральное значение, не измерено");
|
||
await expect(semantics).toContainText("смысловой анализ недоступен");
|
||
const percentile = explanation.locator('[data-component="percentile"]');
|
||
await expect(percentile).toContainText("Нет значения");
|
||
await expect(percentile).toContainText("меньше 30 человек");
|
||
await expect(explanation.locator('[data-component="competition"]')).toContainText(
|
||
"Вклада от соревнований нет. Это не штраф.",
|
||
);
|
||
await expect(confirmed.getByText("Обязательные навыки")).toBeVisible();
|
||
await expect(confirmed.getByText("Только заявлено кандидатом")).toBeVisible();
|
||
|
||
await toggle.click();
|
||
await expect(toggle).toHaveAttribute("aria-expanded", "false");
|
||
await expect(confirmed.getByText("Как получена позиция")).toHaveCount(0);
|
||
|
||
// The group "near" names the weak required skill as a partial source.
|
||
const near = groupSection(page, "Близкие варианты").getByRole("article");
|
||
await expect(near.getByText("Подтверждено частично")).toBeVisible();
|
||
// A profile without a confirmed grade shows no percentile and no rank.
|
||
const network = groupSection(page, "Грейд не подтвержден").getByRole("article").first();
|
||
await network.getByRole("button", { name: /объяснение/ }).click();
|
||
const unconfirmedExplanation = network.getByRole("region", { name: "Объяснение позиции" });
|
||
await expect(unconfirmedExplanation.locator('[data-component="coverage"]')).toHaveText("0,38");
|
||
await expect(unconfirmedExplanation.locator('[data-component="percentile"]')).toHaveCount(0);
|
||
await expect(unconfirmedExplanation.locator('[data-component="rank"]')).toHaveCount(0);
|
||
await expect(network.getByText("Пробел: подтверждения нет")).toBeVisible();
|
||
});
|
||
|
||
test("explains the matches by meaning without a repository address", async ({ page }) => {
|
||
const entry = confirmedEntry(handleA, "middle", 0.853333, {
|
||
semantic_evidence: semanticEvidence,
|
||
unknown_flags: [{ component: "percentile", reason: "cohort_below_30" }],
|
||
});
|
||
const card = {
|
||
pseudonym: handleA,
|
||
categories: null,
|
||
stack: ["go"],
|
||
self_assessment: null,
|
||
experience_band: null,
|
||
work_formats: null,
|
||
salary_compatibility: null,
|
||
projects: [
|
||
{
|
||
title: "Платежный шлюз",
|
||
description: "Проводки и сверки платежей.",
|
||
stack: ["Go", "PostgreSQL"],
|
||
repository_verified: true,
|
||
},
|
||
],
|
||
};
|
||
await installFakeApi(page, {
|
||
searches: [threeGroups({ groups: { main: [entry], near: [], unconfirmed: [] } })],
|
||
card,
|
||
});
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
const confirmed = groupSection(page, "Подтвержденные").getByRole("article");
|
||
const why = confirmed.getByRole("region", { name: "Почему в подборке" });
|
||
await expect(why.getByRole("heading", { name: "Совпадения по смыслу" })).toBeVisible();
|
||
const rows = why.getByRole("listitem").filter({ hasText: "сходство" });
|
||
await expect(rows).toHaveCount(2);
|
||
await expect(rows.nth(0)).toContainText("Разработать сервис сверки платежей");
|
||
await expect(rows.nth(0)).toContainText("Проект");
|
||
await expect(rows.nth(0)).toContainText("Платежный шлюз");
|
||
await expect(rows.nth(0)).toContainText("Высокое сходство");
|
||
await expect(rows.nth(0)).toContainText("Публичный репозиторий");
|
||
await expect(rows.nth(1)).toContainText("Стек");
|
||
await expect(rows.nth(1)).toContainText("Среднее сходство");
|
||
await expect(rows.nth(1)).not.toContainText("Публичный репозиторий");
|
||
await expect(why.getByText("смысловой анализ недоступен")).toHaveCount(0);
|
||
await expect(confirmed.locator('a[href*="github"]')).toHaveCount(0);
|
||
await expectNoHorizontalOverflow(page);
|
||
|
||
await confirmed.getByRole("button", { name: /Открыть карточку/ }).click();
|
||
const panel = confirmed.getByRole("region", { name: "Карточка кандидата" });
|
||
await expect(panel.getByRole("heading", { name: "Проекты" })).toBeVisible();
|
||
await expect(panel.getByText("Подтвержден публичным репозиторием")).toBeVisible();
|
||
expect(await panel.innerText()).not.toMatch(/github\.com/);
|
||
await captureReview(page, "match-semantic-evidence");
|
||
});
|
||
|
||
test("keeps the unavailable wording in the meaning block when ML was down", async ({ page }) => {
|
||
await installFakeApi(page);
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
const why = groupSection(page, "Подтвержденные")
|
||
.getByRole("article")
|
||
.getByRole("region", { name: "Почему в подборке" });
|
||
await expect(why.getByText("Совпадения по смыслу: смысловой анализ недоступен.")).toBeVisible();
|
||
});
|
||
|
||
test("explains a partial output without a count", async ({ page }) => {
|
||
await installFakeApi(page, { searches: [threeGroups({ truncated: true })] });
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
await expect(
|
||
page.getByText("Показана часть выдачи; квота просмотров или предел группы"),
|
||
).toBeVisible();
|
||
await expect(page.getByText(/всего|из \d+/i)).toHaveCount(0);
|
||
});
|
||
|
||
test("keeps the filters on after an empty result and explains it", async ({ page }) => {
|
||
const calls = await installFakeApi(page, { searches: [emptyGroups()] });
|
||
await openSearch(page);
|
||
await page.getByLabel("Подтвержденный грейд").selectOption("senior");
|
||
await page.getByRole("checkbox", { name: "Kafka" }).check();
|
||
await runSearch(page);
|
||
|
||
expect(calls.searches).toEqual([{ filters: { confirmed_grade: "senior", stack: ["kafka"] } }]);
|
||
await expect(page.getByText("По этим условиям никого не нашли")).toBeVisible();
|
||
await expect(page.getByText("поиск не ослабляет их сам")).toBeVisible();
|
||
await expect(page.getByRole("status").getByText("Подтвержденный грейд: Senior")).toBeVisible();
|
||
await expect(
|
||
page.getByRole("status").getByText("Технологии в карточке (нужны все): Kafka"),
|
||
).toBeVisible();
|
||
// Nothing was relaxed: the form still holds both mandatory filters.
|
||
await expect(page.getByLabel("Подтвержденный грейд")).toHaveValue("senior");
|
||
await expect(page.getByRole("checkbox", { name: "Kafka" })).toBeChecked();
|
||
expect(calls.searches).toHaveLength(1);
|
||
});
|
||
|
||
test("shows the Retry-After of a card read refused by the quota", async ({ page }) => {
|
||
await installFakeApi(page, { cardStatus: 429, cardRetryAfter: "120" });
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
const confirmed = groupSection(page, "Подтвержденные").getByRole("article");
|
||
await confirmed.getByRole("button", { name: /Открыть карточку/ }).click();
|
||
const panel = confirmed.getByRole("region", { name: "Карточка кандидата" });
|
||
await expect(panel.getByText("Квота просмотров карточек исчерпана")).toBeVisible();
|
||
await expect(panel.getByText(/через 2 мин/)).toBeVisible();
|
||
await expect(panel.getByRole("button", { name: "Повторить" })).toBeVisible();
|
||
await captureReview(page, "match-search-quota");
|
||
});
|
||
|
||
test("names no hidden case when the card is no longer visible", async ({ page }) => {
|
||
await installFakeApi(page, { cardStatus: 404 });
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
const confirmed = groupSection(page, "Подтвержденные").getByRole("article");
|
||
await confirmed.getByRole("button", { name: /Открыть карточку/ }).click();
|
||
const panel = confirmed.getByRole("region", { name: "Карточка кандидата" });
|
||
await expect(panel.getByText("Карточка сейчас недоступна")).toBeVisible();
|
||
await expect(panel.getByText("Причина не раскрывается")).toBeVisible();
|
||
});
|
||
|
||
test("opens the full card with its evidence and no contacts", async ({ page }) => {
|
||
const calls = await installFakeApi(page);
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
const confirmed = groupSection(page, "Подтвержденные").getByRole("article");
|
||
// The label changes from "Открыть карточку" to "Закрыть карточку".
|
||
const open = confirmed.getByRole("button", { name: /карточку/ });
|
||
await open.click();
|
||
const panel = confirmed.getByRole("region", { name: "Карточка кандидата" });
|
||
await expect(panel.getByText("Backend: Middle. Сильное подтверждение")).toBeVisible();
|
||
await expect(panel.getByText("Заявлено: Junior")).toBeVisible();
|
||
await expect(panel.getByText("Backend: Middle").first()).toBeVisible();
|
||
await expect(panel.getByText("Год оценки")).toBeVisible();
|
||
await expect(panel.getByText("Результат теста")).toBeVisible();
|
||
await expect(panel.getByText(/демонстрац|откалиброван|Калибровка/)).toHaveCount(0);
|
||
await expect(panel.getByText("Нет значения в карточке")).toBeVisible();
|
||
expect(await panel.innerText()).not.toMatch(/@|\+\d{6}/);
|
||
|
||
// Closing and opening again does not read the card a second time.
|
||
await open.click();
|
||
await expect(panel).toBeHidden();
|
||
await open.click();
|
||
await expect(panel).toBeVisible();
|
||
expect(calls.paths.filter((path) => path.includes("/candidate-cards/")).length).toBe(2);
|
||
});
|
||
|
||
test("handles a failed search with a retry and a refused one without a retry", async ({
|
||
page,
|
||
}) => {
|
||
const calls = await installFakeApi(page, { searchStatus: 500 });
|
||
await openSearch(page);
|
||
await page.getByRole("button", { name: "Найти кандидатов" }).click();
|
||
const alert = page.getByRole("alert");
|
||
await expect(alert).toContainText("Не удалось выполнить поиск");
|
||
await expect(alert.getByRole("button", { name: "Повторить" })).toBeVisible();
|
||
expect(calls.searches).toHaveLength(1);
|
||
});
|
||
|
||
test("refuses the search to an account that is not the owner", async ({ page }) => {
|
||
const calls = await installFakeApi(page, { role: "recruiter" });
|
||
await page.goto(`/employer/candidates?organization_id=${orgId}`);
|
||
await expect(page.getByText("Нужны права владельца компании")).toBeVisible();
|
||
await expect(page.getByRole("button", { name: "Найти кандидатов" })).toHaveCount(0);
|
||
expect(calls.searches).toEqual([]);
|
||
});
|
||
|
||
test("searches by a need with its requirements version and keeps the declared grade apart", async ({
|
||
page,
|
||
}) => {
|
||
const calls = await installFakeApi(page, {
|
||
needs: [{ id: needId, title: "Платежный backend" }],
|
||
requirementsVersion: 3,
|
||
searches: [
|
||
threeGroups({ source: { kind: "need", need_id: needId, requirements_version: 3 } }),
|
||
],
|
||
});
|
||
await page.goto(`/employer/candidates?organization_id=${orgId}&need_id=${needId}`);
|
||
await expect(page.getByRole("radio", { name: "По потребности" })).toBeChecked();
|
||
await expect(page.getByLabel("Потребность")).toHaveValue(needId);
|
||
await expect(page.getByText("Версия требований: 3")).toBeVisible();
|
||
await page.getByLabel("Заявленный кандидатом грейд").selectOption("middle");
|
||
await runSearch(page);
|
||
|
||
expect(calls.searches).toEqual([
|
||
{
|
||
need_id: needId,
|
||
requirements_version: 3,
|
||
filters: { declared_grade: "middle" },
|
||
},
|
||
]);
|
||
await expect(
|
||
page.getByText("Потребность «Платежный backend», версия требований 3"),
|
||
).toBeVisible();
|
||
await expect(
|
||
page.getByText("Заявленный грейд (не подтверждение): Middle", { exact: true }),
|
||
).toBeVisible();
|
||
});
|
||
|
||
test("blocks a need search until a need is chosen", async ({ page }) => {
|
||
const calls = await installFakeApi(page, {
|
||
needs: [{ id: needId, title: "Платежный backend" }],
|
||
});
|
||
await openSearch(page);
|
||
await expect(page.getByRole("radio", { name: "По потребности" })).toBeChecked();
|
||
await expect(page.getByText("Выберите потребность.")).toBeVisible();
|
||
// The button is aria-disabled; a forced click and Enter must not search either.
|
||
await page.getByRole("button", { name: "Найти кандидатов" }).click({ force: true });
|
||
await page.getByLabel("Заявленный кандидатом грейд").focus();
|
||
await page.keyboard.press("Enter");
|
||
expect(calls.searches).toEqual([]);
|
||
await page.getByRole("radio", { name: "По всем профилям" }).check();
|
||
await runSearch(page);
|
||
expect(calls.searches).toEqual([{ filters: {} }]);
|
||
});
|
||
|
||
test("keeps cards and the invitation reachable by keyboard at every width", async ({ page }) => {
|
||
await installFakeApi(page);
|
||
await openSearch(page);
|
||
await runSearch(page);
|
||
|
||
await page.setViewportSize({ width: 360, height: 800 });
|
||
const confirmedInvite = groupSection(page, "Подтвержденные").getByRole("link", {
|
||
name: /^Пригласить/,
|
||
});
|
||
const unconfirmedInvite = groupSection(page, "Грейд не подтвержден")
|
||
.getByRole("link", { name: /^Пригласить/ })
|
||
.first();
|
||
await focusByTab(page, confirmedInvite);
|
||
await focusByTab(page, unconfirmedInvite);
|
||
await expect(unconfirmedInvite).toBeInViewport();
|
||
const toggle = groupSection(page, "Подтвержденные").getByRole("button", { name: /объяснение/ });
|
||
await focusByTab(page, toggle);
|
||
await page.keyboard.press("Space");
|
||
await expect(toggle).toHaveAttribute("aria-expanded", "true");
|
||
await expectNoHorizontalOverflow(page);
|
||
await captureReview(page, "match-search-explanation");
|
||
});
|
||
});
|