347 lines
16 KiB
TypeScript
347 lines
16 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 { 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; telegramProblem?: string | null };
|
||
}
|
||
|
||
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:not(.example-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).toContain("Примеров пока нет. Нажмите «Найти новые»");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Примеры помечены (FRTVL-9)", () => {
|
||
it("Scenario: Карточка-пример помечена, настоящая — нет", async () => {
|
||
api.internships = [{ ...cards[0]!, sourceUrl: "https://hotel.com/jobs" }, cards[1]!];
|
||
await loadPage();
|
||
const marks = [...document.querySelectorAll(".card")].map((c) => c.querySelector(".example-badge")?.textContent ?? null);
|
||
expect(marks).toEqual([null, "Пример"]);
|
||
});
|
||
|
||
it("Scenario: Список пуст — предупреждение не обещает примеры", async () => {
|
||
api.internships = [];
|
||
api.tokenRequired = true;
|
||
await loadPage();
|
||
expect($("mock-note").hidden).toBe(false);
|
||
expect($("mock-note").textContent).not.toContain("Сейчас показаны примеры");
|
||
expect($("mock-note").textContent).toContain("Сейчас их нет");
|
||
expect($("empty").textContent).toContain("Введите код доступа и нажмите «Найти новые»");
|
||
expect(document.body.textContent).not.toContain("список появится ниже");
|
||
});
|
||
|
||
it("Scenario: Предупреждение сверху", async () => {
|
||
await loadPage();
|
||
const note = $("mock-note");
|
||
expect(note.hidden).toBe(false);
|
||
expect(note.textContent).toContain("Сейчас показаны примеры");
|
||
expect(note.compareDocumentPosition($("list")) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||
expect(note.compareDocumentPosition(document.querySelector(".settings")!) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
|
||
});
|
||
});
|
||
|
||
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($("telegram-status").textContent).toBe("Телеграм не привязан"));
|
||
expect(document.getElementById("enabled-hint")).toBeNull();
|
||
expect($("settings-hint").textContent).toBe("");
|
||
const text = document.querySelector(".settings")!.textContent!;
|
||
expect(text.match(/не привязан/g)).toHaveLength(1);
|
||
expect((document.getElementById("enabled") as HTMLInputElement).disabled).toBe(true);
|
||
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();
|
||
const fields = document.querySelectorAll("input:not([type=hidden]), select");
|
||
expect(fields.length).toBeGreaterThan(0);
|
||
for (const field of fields) {
|
||
const label = field.closest("label");
|
||
expect(label?.textContent?.replace(/\s+/g, "").length, field.id).toBeGreaterThan(0);
|
||
}
|
||
});
|
||
|
||
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:not(.example-badge)")].map((node) => node.textContent);
|
||
expect(marks).toEqual(["новое", "уверенность: средняя", "смежная"]);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Привязка Телеграма и включение регулярного поиска", () => {
|
||
it("Scenario: Без привязки об этом написано, включить нельзя", async () => {
|
||
await loadPage();
|
||
await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм не привязан"));
|
||
expect(($("enabled") as unknown as HTMLInputElement).disabled).toBe(true);
|
||
expect($("settings-last-run").textContent).toBe("Ежедневный поиск: выключен");
|
||
expect($("settings-last-run").textContent).not.toContain("не запускался");
|
||
});
|
||
|
||
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, linked: true, enabled: false, telegram: "telegram" };
|
||
await loadPage();
|
||
await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм привязан"));
|
||
const text = document.querySelector(".settings")!.textContent!;
|
||
expect(text.match(/Телеграм привязан/g)).toHaveLength(1);
|
||
expect($("settings-hint").textContent).toContain("галочку");
|
||
});
|
||
|
||
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));
|
||
const text = document.querySelector(".settings")!.textContent!;
|
||
expect(text.match(/Откройте бота/g)).toHaveLength(1);
|
||
});
|
||
});
|
||
|
||
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($("mock-confirm").textContent).toBe("Подтвердить привязку");
|
||
const ids = [...document.querySelectorAll(".settings .row button, .settings .row a")].map((e) => e.id);
|
||
expect(ids.indexOf("link-button")).toBeLessThan(ids.indexOf("mock-confirm"));
|
||
expect($("link-code").textContent).toBe("abc");
|
||
expect($("link-info").textContent).toContain("Откройте бота, нажмите Start и отправьте код");
|
||
expect($("mock-confirm").hidden).toBe(false);
|
||
expect($("unlink-button").hidden).toBe(true);
|
||
expect($("link-button").hidden).toBe(true);
|
||
});
|
||
|
||
it("Scenario: Не привязан — видна только кнопка «Привязать»", async () => {
|
||
await loadPage();
|
||
await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм не привязан"));
|
||
expect($("link-button").hidden).toBe(false);
|
||
expect($("mock-confirm").hidden).toBe(true);
|
||
expect($("unlink-button").hidden).toBe(true);
|
||
expect($("telegram-note").textContent).toContain("Бот ещё не настроен");
|
||
});
|
||
|
||
it("Scenario: Привязан — видна только кнопка «Отвязать»", async () => {
|
||
api.settings = { ...api.settings, linked: true, telegram: "telegram" };
|
||
await loadPage();
|
||
await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм привязан"));
|
||
expect($("link-button").hidden).toBe(true);
|
||
expect($("mock-confirm").hidden).toBe(true);
|
||
expect($("unlink-button").hidden).toBe(false);
|
||
});
|
||
|
||
it("Scenario: Ключ не дошёл до сервиса — причина и «Подробнее»", async () => {
|
||
api.settings = { ...api.settings, telegram: "mock", telegramProblem: "no_token" };
|
||
await loadPage();
|
||
await vi.waitFor(() => expect($("telegram-note").textContent).toContain("ключ Телеграм-бота не дошёл до сервиса"));
|
||
expect($("telegram-details").hidden).toBe(false);
|
||
expect($("telegram-detail").textContent).toBe("Нет TELEGRAM_BOT_TOKEN в окружении сервиса.");
|
||
});
|
||
|
||
it("Scenario: Бот работает — «Подробнее» о настройке бота не показывается", async () => {
|
||
api.settings = { ...api.settings, telegram: "telegram", telegramProblem: null };
|
||
await loadPage();
|
||
await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм не привязан"));
|
||
expect($("telegram-details").hidden).toBe(true);
|
||
});
|
||
|
||
it("Scenario: Нет слов «демо» и «токен» на экране", async () => {
|
||
await loadPage();
|
||
expect(document.body.textContent).not.toMatch(/демо|токен|Claude API/i);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Подписи полей (FRTVL-7)", () => {
|
||
it("Scenario: У каждого поля есть подпись", async () => {
|
||
api.tokenRequired = true;
|
||
await loadPage();
|
||
const label = (id: string) => $(id).closest("label")?.querySelector(".field-label")?.textContent;
|
||
expect(label("token")).toBe("Код доступа");
|
||
expect(label("filter-country")).toBe("Страна");
|
||
expect(label("filter-language")).toBe("Язык");
|
||
expect([...document.querySelectorAll("#link-info .field-label")].map((e) => e.textContent)).toEqual(["Бот:", "Код привязки:"]);
|
||
expect(document.querySelector("#link-info")?.textContent).not.toMatch(/привязки\s+:/);
|
||
});
|
||
|
||
it("Scenario: Сказано, у кого взять код доступа", async () => {
|
||
await loadPage();
|
||
expect($("token-hint").textContent).toContain("выдаёт владелец сервиса");
|
||
});
|
||
});
|