freetravel/test/page.test.ts
Peppa 20028b790b
All checks were successful
peppa/lint lint: success за 1с
peppa/typecheck typecheck: success за 2с
peppa/test test: success за 1с
peppa/build build: success за 1с
ci / checks (pull_request) Successful in 15s
deploy / deploy (pull_request) Successful in 13s
FRTVL-2: регулярный поиск раз в сутки и уведомления в Телеграм
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 22:59:33 +05:00

172 lines
7.2 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 () => {
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);
});
});