192 lines
9.6 KiB
TypeScript
192 lines
9.6 KiB
TypeScript
// @vitest-environment happy-dom
|
||
import { readFileSync } from "node:fs";
|
||
import path from "node:path";
|
||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||
import { forumApply, forumEmptyMessage, forumProof, forumSpeakerTerms, forumTravel } from "../public/filters.js";
|
||
import { emptyForumCatalog, mergeForums, sortForums } from "../src/domain/forum.js";
|
||
import { mockForums } from "../src/search/mockForumProvider.js";
|
||
|
||
/** Сценарии страницы для вида «Форумы для выступлений (СНГ)» (FRTVL-45) на МОКЕ API. */
|
||
|
||
const html = readFileSync(path.join(process.cwd(), "public/index.html"), "utf8");
|
||
const body = html.slice(html.indexOf("<body>") + 6, html.indexOf("<script"));
|
||
const TODAY = new Date().toISOString().slice(0, 10);
|
||
const forums = sortForums(mergeForums(emptyForumCatalog(), mockForums(TODAY), "run-f", new Date().toISOString()).catalog, TODAY);
|
||
|
||
interface Api {
|
||
forums: unknown[];
|
||
forumRun: unknown;
|
||
forumRunning: boolean;
|
||
forumsAvailable: boolean;
|
||
searches: string[];
|
||
}
|
||
let api: Api;
|
||
|
||
const json = (data: unknown, status = 200) =>
|
||
Promise.resolve(new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } }));
|
||
|
||
function installFetch() {
|
||
vi.stubGlobal(
|
||
"fetch",
|
||
vi.fn((url: string, init?: RequestInit) => {
|
||
const run = { status: "ok", found: 1, added: 0, rejected: 0, startedAt: "2026-11-25T10:03:00", finishedAt: "2026-11-25T10:05:00" };
|
||
if (url === "/api/internships") return json({ internships: [], lastRun: run });
|
||
if (url === "/api/trainings") return json({ trainings: [], lastRun: run });
|
||
if (url === "/api/forums") return json({ forums: api.forums, lastRun: api.forumRun });
|
||
if (url === "/api/session") return json({ signedIn: true, loginAvailable: true });
|
||
if (url.startsWith("/api/settings")) return json({ enabled: false, linked: false, linkUrl: null, telegram: "mock", lastRun: null });
|
||
if (url.startsWith("/api/search/status")) {
|
||
const isForum = url.endsWith("?kind=forums");
|
||
return json({
|
||
state: isForum && api.forumRunning ? "running" : "idle",
|
||
provider: "mock",
|
||
signedIn: true,
|
||
loginAvailable: true,
|
||
trainingsAvailable: true,
|
||
forumsAvailable: api.forumsAvailable,
|
||
lastRun: isForum ? api.forumRun : run,
|
||
});
|
||
}
|
||
if (url.startsWith("/api/search") && init?.method === "POST") {
|
||
api.searches.push(url);
|
||
if (url.endsWith("?kind=forums")) api.forumRunning = true;
|
||
return json({ state: "running" }, 202);
|
||
}
|
||
return json({}, 404);
|
||
}),
|
||
);
|
||
}
|
||
|
||
async function loadPage() {
|
||
document.body.innerHTML = body;
|
||
vi.resetModules();
|
||
await import("../public/app.js");
|
||
await vi.waitFor(() => expect(document.getElementById("run-summary")!.textContent).not.toBe(""));
|
||
}
|
||
|
||
const $ = (id: string) => document.getElementById(id) as HTMLElement & { value: string };
|
||
const radio = (value: string) => document.querySelector(`input[name="kind"][value="${value}"]`) as HTMLInputElement;
|
||
|
||
async function chooseForums() {
|
||
radio("forums").checked = true;
|
||
radio("forums").dispatchEvent(new Event("change"));
|
||
await vi.waitFor(() => expect($("run-summary").textContent).toContain("Последний поиск форумов"));
|
||
}
|
||
|
||
beforeEach(() => {
|
||
api = { forums, forumRun: null, forumRunning: false, forumsAvailable: true, searches: [] };
|
||
installFetch();
|
||
});
|
||
afterEach(() => {
|
||
vi.unstubAllGlobals();
|
||
vi.useRealTimers();
|
||
});
|
||
|
||
describe("Requirement: Карточка форума (страница)", () => {
|
||
it("Scenario: Полная карточка форума", async () => {
|
||
await loadPage();
|
||
expect($("kind-forums").hidden).toBe(false);
|
||
expect(radio("forums").closest("label")?.textContent?.trim()).toBe("Форумы для выступлений (СНГ)");
|
||
await chooseForums();
|
||
expect($("language-field").hidden).toBe(true);
|
||
expect($("country-hint").textContent).toBe("Где проходит форум");
|
||
const cards = document.querySelectorAll(".forum-card");
|
||
expect(cards).toHaveLength(3);
|
||
const almaty = [...cards].find((card) => card.textContent?.includes("Форум клиентского опыта"))!;
|
||
const terms = [...almaty.querySelectorAll("dt")].map((node) => node.textContent);
|
||
expect(terms).toEqual([
|
||
"Организатор",
|
||
"Где",
|
||
"Даты",
|
||
"Дедлайн заявки",
|
||
"Формат",
|
||
"Тематика",
|
||
"Как подать заявку",
|
||
"Условия для спикера",
|
||
"Поездка и проживание",
|
||
"Проверено",
|
||
"Подтверждение",
|
||
]);
|
||
expect(almaty.textContent).toContain("Алматы, Казахстан");
|
||
const links = [...almaty.querySelectorAll("a")].map((a) => [a.textContent, a.getAttribute("href")]);
|
||
expect(links).toEqual([
|
||
["Открытый отбор спикеров", "https://example.org/mock/almaty-cx-forum/speakers"],
|
||
["Страница организатора", "https://example.org/mock/almaty-cx-forum"],
|
||
]);
|
||
expect(almaty.querySelector(".unconfirmed")).toBeNull();
|
||
expect(almaty.textContent).toContain("в ближайшие 3 месяца");
|
||
expect($("mock-note-text").textContent).toBe("Это примеры, не настоящие форумы. Настоящий поиск ещё не включён.");
|
||
});
|
||
|
||
it("Scenario: Условие неизвестно — заметная отметка", async () => {
|
||
await loadPage();
|
||
await chooseForums();
|
||
const marked = document.querySelectorAll(".forum-card .unconfirmed");
|
||
expect(marked).toHaveLength(1);
|
||
expect(marked[0]?.textContent).toContain("Бесплатное выступление не подтверждено");
|
||
expect(marked[0]?.closest(".forum-card")?.textContent).toContain("Митап операторов поддержки");
|
||
});
|
||
|
||
it("Scenario: Ближайший дедлайн первым", async () => {
|
||
await loadPage();
|
||
await chooseForums();
|
||
const titles = [...document.querySelectorAll(".forum-card h2")].map((node) => node.firstChild?.textContent);
|
||
expect(titles).toEqual(["Митап операторов поддержки", "Форум клиентского опыта", "Конференция «Сервис в гостеприимстве»"]);
|
||
});
|
||
|
||
it("Scenario: Поиск форумов запускается своей кнопкой", async () => {
|
||
api.forums = [];
|
||
await loadPage();
|
||
await chooseForums();
|
||
vi.useFakeTimers();
|
||
$("search-form").dispatchEvent(new Event("submit", { cancelable: true }));
|
||
await vi.waitFor(() => expect($("search-state").textContent).toMatch(/^Поиск начался/));
|
||
expect(api.searches).toEqual(["/api/search?kind=forums"]);
|
||
api.forumRunning = false;
|
||
api.forums = forums;
|
||
api.forumRun = { status: "ok", found: 3, added: 3, rejected: 2, startedAt: "2026-11-25T10:03:00", finishedAt: "2026-11-25T10:05:00" };
|
||
await vi.advanceTimersByTimeAsync(3100);
|
||
vi.useRealTimers();
|
||
await vi.waitFor(() => expect(document.querySelectorAll(".forum-card")).toHaveLength(3));
|
||
});
|
||
|
||
it("Scenario: Ничего не найдено", async () => {
|
||
api.forums = [];
|
||
api.forumRun = { status: "ok", found: 0, added: 0, rejected: 4, startedAt: "2026-11-25T10:03:00", finishedAt: "2026-11-25T10:05:00" };
|
||
await loadPage();
|
||
await chooseForums();
|
||
expect($("empty").textContent).toBe(
|
||
"Поиск выполнен 25.11.2026: подходящих форумов сейчас нет. Новые форумы объявляют регулярно — запустите поиск позже.",
|
||
);
|
||
});
|
||
|
||
it("без форумов на сервере вариант не показывается", async () => {
|
||
api.forumsAvailable = false;
|
||
await loadPage();
|
||
expect($("kind-forums").hidden).toBe(true);
|
||
expect($("kind-trainings").hidden).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe("Тексты форумов", () => {
|
||
it("условия словами", () => {
|
||
expect(forumTravel({ travel: "partial", travelDetails: "проживание оплачено" })).toBe(
|
||
"частично оплачивает организатор — проживание оплачено",
|
||
);
|
||
expect(forumTravel({ travel: "unknown", travelDetails: "" })).toBe("не указано");
|
||
expect(forumSpeakerTerms({ speakerCost: "free", speakerTerms: "" })).toBe("выступление бесплатное");
|
||
expect(forumSpeakerTerms({ speakerCost: "unknown", speakerTerms: "" })).toBe("условия не указаны");
|
||
expect(forumApply({ applyMethod: "propose_topic", applyDetails: "" })).toBe("предложить тему организатору");
|
||
expect(forumProof({ callUrl: null, organizerContact: "a@b.kz" })).toEqual({ label: "Контакт организатора", url: null, text: "a@b.kz" });
|
||
expect(forumProof({ callUrl: null, organizerContact: null })).toBeNull();
|
||
});
|
||
|
||
it("пустой список и ошибка поиска", () => {
|
||
expect(forumEmptyMessage(0, 0, true, null)).toContain("Нажмите «Найти новые»");
|
||
expect(forumEmptyMessage(0, 0, false, null)).toContain("войдите, если это вы");
|
||
expect(forumEmptyMessage(0, 0, true, { status: "error" })).toBe("Поиск форумов не удался. Нажмите «Найти новые» ещё раз чуть позже.");
|
||
expect(forumEmptyMessage(2, 0, true, null)).toContain("выберите «Все»");
|
||
expect(forumEmptyMessage(2, 2, true, null)).toBeNull();
|
||
});
|
||
});
|