Files

330 lines
15 KiB
TypeScript

import { QueryClientProvider } from "@tanstack/react-query";
import { renderToString } from "react-dom/server";
import { StaticRouterProvider, createStaticHandler, createStaticRouter } from "react-router-dom";
import { describe, expect, it } from "vitest";
import { assessmentQueryKeys } from "../../entities/assessment";
import { candidateViewQueryKeys } from "../../entities/candidate-view";
import { getListMyConsentsQueryKey } from "../../shared/api/endpoints/consent/consent";
import { getGetCurrentSessionQueryKey } from "../../shared/api/endpoints/identity/identity";
import type { Session } from "../../shared/api/schemas";
import { createQueryClient } from "../providers/query-client";
import { routes } from "./routes";
// Node has no DOM in this project's Vitest setup, so routes are rendered
// through React Router's static handler: the same route tree, loaders, and
// layouts as in the browser, checked as server-rendered HTML.
async function render(path: string): Promise<string | Response> {
const handler = createStaticHandler(routes);
const context = await handler.query(new Request(`http://localhost${path}`));
if (context instanceof Response) {
return context;
}
const router = createStaticRouter(handler.dataRoutes, context);
const queryClient = createQueryClient();
const scenario = path.startsWith("/employer") ? "employer" : "candidate";
if (path.startsWith("/candidate") || path.startsWith("/employer")) {
const session = {
account: {
id: "11111111-1111-4111-8111-111111111111",
email: "person@example.test",
email_verified: true,
scenario,
onboarding_step:
path === "/candidate/onboarding"
? "candidate_consents"
: path === "/candidate/profile"
? "candidate_profile"
: path === "/candidate/assessment"
? "candidate_assessment"
: scenario === "candidate"
? "completed"
: "employer_company",
created_at: "2026-10-07T12:00:00Z",
},
csrf_token: "A".repeat(43),
} satisfies Session;
queryClient.setQueryData(getGetCurrentSessionQueryKey(), session);
if (path === "/candidate/assessment") {
queryClient.setQueryData(assessmentQueryKeys.availability(session), { specializations: [] });
queryClient.setQueryData(assessmentQueryKeys.questionnaire(session), {
version: 0,
specializations: [],
work_context: null,
updated_at: null,
});
}
}
if (path.startsWith("/candidate/privacy")) {
const hasMore = path.includes("history=partial");
const actorId = "11111111-1111-4111-8111-111111111111";
queryClient.setQueryData(candidateViewQueryKeys.settings(actorId), {
publication: {
state: "closed",
closed_reason: "never_published",
fields: [],
consent_id: null,
published_at: null,
version: 0,
},
search_status: {
value: "not_looking",
lapsed: false,
confirmed_at: null,
lapses_at: null,
version: 0,
},
hidden_organizations_total: 0,
});
queryClient.setQueryData(["candidate-view", actorId, "consent-history-ready"], true);
queryClient.setQueryData(getListMyConsentsQueryKey({ limit: 100 }), {
pages: [
{
items: [
{
id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80",
purpose: "c2",
state: "active",
text_version: "c2-2026-10-01",
source: "consent_settings",
granted_at: "2026-10-02T09:00:00Z",
revoked_at: null,
revocation_source: null,
organization: null,
fields: null,
invitation_id: null,
invitation_terms_version: null,
},
{
id: "01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a81",
purpose: "c4",
state: "active",
text_version: "c4-2026-10-01",
source: "invitation_acceptance",
granted_at: "2026-10-03T09:00:00Z",
revoked_at: null,
revocation_source: null,
organization: {
id: "01928f7a-1a2b-7c3d-8e4f-5a6b7c8d9e01",
name: "Первая тестовая компания",
},
fields: ["email"],
invitation_id: "01928f7a-7a8b-7c9d-8e0f-1a2b3c4d5e60",
invitation_terms_version: 1,
},
],
page: { has_more: hasMore, next_cursor: hasMore ? "next-page" : null },
},
],
pageParams: [undefined],
});
}
return renderToString(
<QueryClientProvider client={queryClient}>
<StaticRouterProvider router={router} context={context} hydrate={false} />
</QueryClientProvider>,
);
}
async function renderHtml(path: string): Promise<string> {
const result = await render(path);
if (typeof result !== "string") {
throw new Error(`Expected HTML for ${path}, got a ${result.status} response.`);
}
return result;
}
function count(html: string, pattern: RegExp): number {
return html.match(new RegExp(pattern.source, "g"))?.length ?? 0;
}
function currentLinkText(html: string): string[] {
return [...html.matchAll(/<a[^>]*aria-current="page"[^>]*>(.*?)<\/a>/g)].map(
(match) => match[1] ?? "",
);
}
describe("route groups", () => {
it.each([
["/", "Протокол подтвержденных навыков", "Публичные разделы"],
["/login", "Вход", "Публичные разделы"],
["/register", "Регистрация", "Публичные разделы"],
["/verify-email", "Подтверждение почты", "Публичные разделы"],
["/support", "Поддержка", "Публичные разделы"],
["/terms", "Условия использования", "Публичные разделы"],
["/privacy", "Конфиденциальность", "Публичные разделы"],
["/candidate", "Главная", "Разделы кабинета кандидата"],
["/candidate/profile", "Профиль", "Разделы кабинета кандидата"],
["/candidate/questionnaire", "Анкета", "Разделы кабинета кандидата"],
["/candidate/onboarding", "Первые шаги", "Разделы кабинета кандидата"],
["/candidate/privacy", "Настройки приватности", "Разделы кабинета кандидата"],
["/candidate/assessment", "Проверка знаний", "Разделы кабинета кандидата"],
[
"/candidate/assessment/01928f7a-9c0d-7e1f-8a2b-3c4d5e6f7a80",
"Попытка проверки",
"Разделы кабинета кандидата",
],
["/employer/company", "Компания", "Разделы кабинета работодателя"],
["/employer/needs", "Потребности", "Разделы кабинета работодателя"],
["/candidate/support/cases", "Мои обращения", "Разделы кабинета кандидата"],
["/candidate/support/cases/new", "Обратиться в поддержку", "Разделы кабинета кандидата"],
[
"/candidate/support/cases/manual-assessment",
"Запросить ручную оценку",
"Разделы кабинета кандидата",
],
["/employer/support/cases", "Мои обращения", "Разделы кабинета работодателя"],
["/employer/support/cases/new", "Обратиться в поддержку", "Разделы кабинета работодателя"],
["/employer/candidates", "Кандидаты", "Разделы кабинета работодателя"],
["/employer/invitations/new", "Приглашение кандидату", "Разделы кабинета работодателя"],
["/employer/invitations", "Приглашения", "Разделы кабинета работодателя"],
])("renders %s in its shell with one h1 and landmarks", async (path, heading, navLabel) => {
const html = await renderHtml(path);
expect(count(html, /<h1[\s>]/)).toBe(1);
expect(html).toMatch(new RegExp(`<h1[^>]*>${heading}</h1>`));
expect(html).toMatch(new RegExp(`<nav[^>]*aria-label="${navLabel}"`));
expect(count(html, /<main[\s>]/)).toBe(1);
expect(html).toMatch(/<main[^>]*id="main-content"[^>]*tabindex="-1"/i);
expect(html).toContain(`<title>${heading} - Lincodex</title>`);
});
it("puts the skip link before any other link and points it at main", async () => {
for (const path of ["/", "/candidate", "/employer/needs"]) {
const html = await renderHtml(path);
const firstLink = html.match(/<a[^>]*>(.*?)<\/a>/);
expect(firstLink?.[0]).toContain('href="#main-content"');
expect(firstLink?.[1]).toBe("Перейти к основному содержимому");
}
});
it("links to the public terms and privacy pages from the footer", async () => {
const html = await renderHtml("/");
expect(html).toMatch(/<a[^>]*href="\/terms"[^>]*>Условия использования<\/a>/);
expect(html).toMatch(/<a[^>]*href="\/privacy"[^>]*>Конфиденциальность<\/a>/);
});
it("marks the active cabinet section with aria-current", async () => {
expect(currentLinkText(await renderHtml("/candidate"))).toEqual(["Главная"]);
// The results are a sub-section of the test: the switch segment is the
// page, and the primary "Тест" item is current as the section (true).
const results = await renderHtml("/candidate/results");
expect(currentLinkText(results)).toEqual(["Результаты"]);
expect(results).toMatch(/<a[^>]*aria-current="true"[^>]*>Тест<\/a>/);
// The account menu is rendered for the header and for the phone tab bar.
expect(currentLinkText(await renderHtml("/candidate/privacy"))).toEqual([
"Приватность",
"Приватность",
]);
expect(currentLinkText(await renderHtml("/employer/invitations"))).toEqual(["Приглашения"]);
});
it("separates the cabinets: each shell shows only its own navigation", async () => {
const candidate = await renderHtml("/candidate");
const employer = await renderHtml("/employer/company");
expect(candidate).not.toContain("Разделы кабинета работодателя");
expect(candidate).not.toContain("Публичные разделы");
expect(employer).not.toContain("Разделы кабинета кандидата");
expect(employer).not.toContain("Публичные разделы");
});
it("sends the employer cabinet root to the company screen", async () => {
const result = await render("/employer");
expect(result).toBeInstanceOf(Response);
expect((result as Response).status).toBe(302);
expect((result as Response).headers.get("Location")).toBe("/employer/company");
});
it.each([
["/missing", "/", "На главную"],
["/candidate/missing", "/candidate", "В кабинет кандидата"],
["/employer/missing", "/employer/company", "В кабинет работодателя"],
])("shows a not-found page for %s inside the matching shell", async (path, home, label) => {
const html = await renderHtml(path);
expect(html).toMatch(/<h1[^>]*>Страница не найдена<\/h1>/);
expect(html).toMatch(new RegExp(`<a[^>]*href="${home}"[^>]*>${label}</a>`));
});
});
describe("product readiness", () => {
it("keeps the training run available when no full-assessment category exists", async () => {
const html = await renderHtml("/candidate/assessment");
expect(html).toContain("Сначала выберите специализацию");
expect(html).toContain("Пройти экспресс-тест");
expect(html).not.toContain("Начать полную проверку");
});
it("describes the working cabinets on the root page without the scaffold label", async () => {
const html = await renderHtml("/");
expect(html).toContain("Регистрация, вход и основные сценарии кабинетов уже работают");
expect(html).not.toContain("каркас");
expect(html).not.toContain("Пустой каркас");
expect(html).toContain("Список доступен в кабинете работодателя");
expect(html).toMatch(/<a[^>]*href="\/login"[^>]*>Войти<\/a>/);
expect(html).toMatch(/<a[^>]*href="\/register"[^>]*>Зарегистрироваться<\/a>/);
// The API liveness check lives on the technical page, not on the landing.
expect(html).not.toContain("healthz");
expect(html).toMatch(/<a[^>]*href="\/status"[^>]*>Технический статус<\/a>/);
});
it("labels the status page as technical", async () => {
const html = await renderHtml("/status");
expect(html).toContain("Служебная страница");
expect(html).toContain("Это не показатель готовности продукта");
});
it("renders separate privacy controls while preparing actor-scoped consent history", async () => {
const html = await renderHtml("/candidate/privacy");
expect(html).toContain("Публикация карточки");
expect(html).toContain("Статус поиска");
expect(html).toContain("Подготавливаем историю согласий...");
expect(html).not.toContain("c2-2026-10-01");
expect(html).not.toContain("Первая тестовая компания");
});
it("does not call consent history empty before actor-scoped loading", async () => {
const html = await renderHtml("/candidate/privacy?history=partial");
expect(html).toContain("Подготавливаем историю согласий...");
expect(html).not.toContain("Записей C3 пока нет.");
});
it("links the saved candidate consent step to the same settings screen", async () => {
const html = await renderHtml("/candidate/onboarding");
expect(html).toContain("Состояние шага хранится на сервере");
expect(html).toMatch(
/<a[^>]*href="\/candidate\/privacy"[^>]*>Открыть согласия и настройки приватности<\/a>/,
);
});
it("routes the employer invitation list to its own screen, not a placeholder", async () => {
const html = await renderHtml("/employer/invitations");
expect(html).toMatch(/<h1[^>]*>Приглашения<\/h1>/);
expect(html).toContain("Проверяем компанию...");
expect(html).not.toContain("Экран будет реализован в одной из следующих задач");
expect(html).not.toContain("Заготовка");
});
it("routes the candidate inbox and one invitation to their own screens, not placeholders", async () => {
const inbox = await renderHtml("/candidate/invitations");
expect(inbox).toMatch(/<h1[^>]*>Приглашения<\/h1>/);
expect(inbox).not.toContain("Экран будет реализован в одной из следующих задач");
const detail = await renderHtml(
`/candidate/invitations/${"0".repeat(8)}-0000-4000-8000-000000000000`,
);
expect(detail).toContain("Открываем приглашение...");
expect(detail).not.toContain("Экран будет реализован в одной из следующих задач");
});
});