freetravel/test/page.test.ts
Peppa 610fef7ecb
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 4с
peppa/test test: success за 2с
peppa/build build: success за 2с
ci / checks (pull_request) Successful in 34s
deploy / deploy (pull_request) Successful in 18s
FRTVL-6: галочка и подпись в одну строку, одна короткая подсказка
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:10:34 +05:00

220 lines
9.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { mockInternships } from "../src/search/mockSearchProvider.js";
/** Сценарии страницы (internship-catalog-ui) на МОКЕ API. */
const html = readFileSync(path.join(process.cwd(), "public/index.html"), "utf8");
const body = html.slice(html.indexOf("<body>") + 6, html.indexOf("<script"));
const cards = mockInternships.slice(0, 3).map((item, index) => ({
...item,
id: `card-${index}`,
checkedAt: "2026-11-14T00:00:00.000Z",
firstSeenAt: "2026-11-14T00:00:00.000Z",
addedInRun: "run-1",
isNew: index === 0,
}));
interface ApiState {
internships: typeof cards;
tokenRequired: boolean;
token: string;
running: boolean;
settings: { enabled: boolean; linked: boolean; linkUrl: string | null; telegram: string; lastRun: unknown };
}
let api: ApiState;
function json(data: unknown, status = 200) {
return Promise.resolve(new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json" } }));
}
function installFetch() {
vi.stubGlobal(
"fetch",
vi.fn((url: string, init?: RequestInit) => {
if (url === "/api/internships") {
return json({ internships: api.internships, lastRun: { status: "ok", found: 3, added: 1, rejected: 3 } });
}
if (url === "/api/settings" && (!init?.method || init.method === "GET")) return json(api.settings);
if (url === "/api/settings" && init?.method === "PUT") {
if (!api.settings.linked) return json({ error: "Сначала привяжите Телеграм" }, 409);
api.settings.enabled = JSON.parse(init.body as string).enabled;
return json(api.settings);
}
if (url === "/api/search/status") {
return json({ state: api.running ? "running" : "idle", provider: "mock", tokenRequired: api.tokenRequired });
}
if (url === "/api/search" && init?.method === "POST") {
const auth = (init.headers as Record<string, string> | undefined)?.Authorization;
if (api.tokenRequired && auth !== `Bearer ${api.token}`) return json({ error: "Неверный код доступа" }, 401);
api.running = 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 titles = () =>
[...document.querySelectorAll(".card h2")].map((node) => node.firstChild?.textContent);
beforeEach(() => {
api = {
internships: cards,
tokenRequired: false,
token: "",
running: false,
settings: { enabled: false, linked: false, linkUrl: null, telegram: "mock", lastRun: null },
};
installFetch();
});
afterEach(() => {
vi.unstubAllGlobals();
vi.useRealTimers();
});
describe("Requirement: Список стажировок", () => {
it("Scenario: Каталог с карточками — новые первыми, у каждой ссылка «Источник»", async () => {
await loadPage();
expect(document.querySelectorAll(".card")).toHaveLength(3);
expect(document.querySelector(".card .badge")!.textContent).toBe("новое");
const links = [...document.querySelectorAll(".card a")];
expect(links.map((link) => link.textContent)).toEqual(["Источник", "Источник", "Источник"]);
expect($("mock-note").hidden).toBe(false);
});
it("Scenario: Пустой каталог", async () => {
api.internships = [];
await loadPage();
expect($("empty").textContent).toBe("Пока ничего не найдено — нажмите «Найти новые»");
});
});
describe("Requirement: Фильтры", () => {
it("Scenario: Фильтр по стране", async () => {
await loadPage();
$("filter-country").value = "Турция";
$("filter-country").dispatchEvent(new Event("change"));
expect(titles()).toEqual(["Ассистент гостевого сервиса"]);
});
});
describe("Requirement: Запуск поиска со страницы", () => {
it("Scenario: Поиск со страницы — состояние «Идёт поиск…», затем отчёт", async () => {
api.tokenRequired = true;
api.token = "s3cret";
await loadPage();
expect($("token-label").hidden).toBe(false);
vi.useFakeTimers();
$("token").value = "s3cret";
$("search-form").dispatchEvent(new Event("submit", { cancelable: true }));
await vi.waitFor(() => expect($("search-state").textContent).toBe("Идёт поиск…"));
api.running = false;
await vi.advanceTimersByTimeAsync(3100);
vi.useRealTimers();
await vi.waitFor(() => expect($("search-state").textContent).toBe(""));
expect($("run-summary").textContent).toContain("найдено: 3, новых: 1");
});
it("Scenario: Неверный код доступа", async () => {
api.tokenRequired = true;
api.token = "s3cret";
await loadPage();
$("token").value = "wrong";
$("search-form").dispatchEvent(new Event("submit", { cancelable: true }));
await vi.waitFor(() => expect($("search-state").textContent).toBe("Неверный код доступа"));
});
});
describe("Requirement: Подписи и пустые состояния", () => {
it("Scenario: Телеграм не привязан", async () => {
await loadPage();
await vi.waitFor(() => expect($("enabled-hint").textContent).toBe("Сначала привяжите Телеграм"));
expect($("enabled").closest("label")?.textContent).toContain("Искать раз в сутки");
});
it("Scenario: Поиск ещё не запускался", async () => {
const { runNextStep } = await import("../public/filters.js");
expect(runNextStep(null, true)).toContain("Введите код доступа");
expect(runNextStep(null, false)).toContain("Нажмите «Найти новые»");
expect(runNextStep({}, true)).toBe("");
});
it("Scenario: Код доступа не введён", async () => {
api.tokenRequired = true;
api.token = "s3cret";
await loadPage();
$("token").value = "";
$("search-form").dispatchEvent(new Event("submit", { cancelable: true }));
await vi.waitFor(() => expect($("search-state").textContent).toContain("Введите код доступа"));
});
});
describe("Requirement: Уверенность и смежность", () => {
it("Scenario: Карточка со смежной сферой", async () => {
api.internships = [{ ...cards[0]!, confidence: "medium", adjacent: true } as (typeof cards)[number]];
await loadPage();
const marks = [...document.querySelectorAll(".card .badge")].map((node) => node.textContent);
expect(marks).toEqual(["новое", "уверенность: средняя", "смежная"]);
});
});
describe("Requirement: Привязка Телеграма и включение регулярного поиска", () => {
it("Scenario: Без привязки об этом написано, включить нельзя", async () => {
await loadPage();
await vi.waitFor(() => expect($("settings-hint").textContent).toContain("уведомления не отправляются"));
expect(($("enabled") as unknown as HTMLInputElement).disabled).toBe(true);
expect($("settings-last-run").textContent).toBe("Регулярный поиск ещё не запускался");
});
it("Scenario: Привязан и включён — виден итог последнего запуска", async () => {
api.settings = {
enabled: true,
linked: true,
linkUrl: null,
telegram: "telegram",
lastRun: { at: "2026-11-14T10:00:00.000Z", status: "error", sent: 0, error: "Сервис поиска недоступен" },
};
await loadPage();
await vi.waitFor(() => expect($("settings-hint").textContent).toContain("Регулярный поиск включён"));
expect($("settings-last-run").textContent).toContain("ошибка: Сервис поиска недоступен");
expect(($("enabled") as unknown as HTMLInputElement).checked).toBe(true);
});
});
describe("Requirement: Понятный экран привязки", () => {
it("Scenario: Код привязки на экране", async () => {
api.settings = {
...api.settings,
linkUrl: "https://t.me/peppa_bot?start=abc",
linkCode: "abc",
botUsername: "peppa_bot",
telegram: "telegram",
} as typeof api.settings;
await loadPage();
await vi.waitFor(() => expect($("link-info").hidden).toBe(false));
expect($("bot-name").textContent).toBe("@peppa_bot");
expect($("link-code").textContent).toBe("abc");
expect($("link-info").textContent).toContain("Откройте бота, нажмите Start и отправьте код");
expect($("mock-confirm").hidden).toBe(true);
expect($("unlink-button").hidden).toBe(true);
});
it("Scenario: Нет слов «демо» и «токен» на экране", async () => {
await loadPage();
expect(document.body.textContent).not.toMatch(/демо|токен|Claude API/i);
});
});