// @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("") + 6, html.indexOf(" ({ ...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; botUsername?: string; 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 | 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($("token-error").textContent).toBe("Код не подходит. Уточните его у владельца сервиса."), ); }); }); describe("Requirement: Подписи и пустые состояния", () => { it("Scenario: Телеграм не привязан", async () => { await loadPage(); await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм не привязан")); // FRTVL-24: под галочкой одна подсказка, почему её нельзя отметить expect($("enabled-hint").textContent).toBe("Сначала привяжите Телеграм, иначе присылать некуда."); 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($("token-error").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).toBe("Уведомления временно недоступны."); }); 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).toBe("Уведомления временно недоступны.")); expect($("telegram-details").hidden).toBe(false); expect($("telegram-detail").textContent).toContain("Для владельца: сервис не получил ключ Телеграм-бота"); expect($("telegram-detail").textContent).toContain("TELEGRAM_BOT_TOKEN"); }); it("Scenario: Бот работает — «Подробнее» о настройке бота не показывается", async () => { api.settings = { ...api.settings, telegram: "telegram", botUsername: "nternships_bot", telegramProblem: null }; await loadPage(); await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм не привязан")); expect($("telegram-note").textContent).not.toContain("временно недоступны"); 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("выдаёт владелец сервиса"); }); }); describe("Requirement: Подсказки к полям (FRTVL-19)", () => { it("Scenario: Подсказки у фильтров", async () => { await loadPage(); expect($("country-hint").textContent).toBe("Где проходит стажировка"); expect($("filter-country").getAttribute("aria-describedby")).toBe("country-hint"); expect($("language-hint").textContent).toContain("на русском или без требования к языку"); expect($("filter-language").getAttribute("aria-describedby")).toBe("language-hint"); expect($("token").getAttribute("placeholder")).toBe("Введите код доступа"); }); it("Scenario: Подсказка в блоке Телеграма до привязки", async () => { await loadPage(); await vi.waitFor(() => expect($("telegram-code-hint").textContent).toContain("появится код привязки")); expect($("telegram-code-hint").textContent).toContain("отправить боту"); expect($("telegram-code-hint").textContent).toContain("ничего вводить не нужно"); expect($("telegram-code-hint").textContent).not.toContain("Код доступа"); }); it("Scenario: Блок Телеграма напоминает про код доступа", async () => { api.tokenRequired = true; await loadPage(); await vi.waitFor(() => expect($("telegram-code-hint").textContent).toContain("нужен код доступа из поля «Код доступа» выше")); }); it("Scenario: После привязки подсказки про код нет", async () => { api.settings = { ...api.settings, linked: true, telegram: "telegram" }; await loadPage(); await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм привязан")); expect($("telegram-code-hint").textContent).toBe(""); }); }); describe("Requirement: Понятные ошибки кода доступа (FRTVL-19)", () => { it("Scenario: Пустой код при привязке Телеграма", async () => { api.tokenRequired = true; api.token = "s3cret"; await loadPage(); await vi.waitFor(() => expect($("link-button").hidden).toBe(false)); $("token").value = ""; const fetchMock = vi.mocked(fetch); fetchMock.mockClear(); $("link-button").click(); await vi.waitFor(() => expect($("settings-error").textContent).toBe( "Введите код доступа в поле выше: без него настройки Телеграма не изменить. Код выдаёт владелец сервиса.", ), ); expect(fetchMock.mock.calls.some(([url]) => String(url).includes("/telegram/link"))).toBe(false); }); }); describe("Requirement: Понятная галочка ежедневного поиска (FRTVL-24)", () => { it("Scenario: Телеграм не привязан", async () => { await loadPage(); await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм не привязан")); expect(($("enabled") as unknown as HTMLInputElement).disabled).toBe(true); expect($("enabled-hint").textContent).toBe("Сначала привяжите Телеграм, иначе присылать некуда."); expect($("enabled").getAttribute("aria-describedby")).toBe("enabled-hint"); }); it("Scenario: Отметили галочку", async () => { api.settings = { ...api.settings, linked: true, enabled: false, telegram: "telegram" }; const installed = fetch as unknown as (url: string, init?: RequestInit) => Promise; vi.stubGlobal( "fetch", vi.fn((url: string, init?: RequestInit) => { if (url === "/api/settings" && (!init?.method || init.method === "GET")) { return json({ ...api.settings, nextRunAt: api.settings.enabled ? "2026-11-18T09:30:00.000Z" : null }); } return installed(url, init); }), ); await loadPage(); await vi.waitFor(() => expect($("settings-last-run").textContent).toBe("Ежедневный поиск: выключен")); expect($("enabled-hint").textContent).toBe(""); const box = $("enabled") as unknown as HTMLInputElement; box.checked = true; box.dispatchEvent(new Event("change")); const when = new Date("2026-11-18T09:30:00.000Z").toLocaleString("ru-RU"); await vi.waitFor(() => expect($("settings-last-run").textContent).toBe(`Ежедневный поиск: включён, следующий запуск ${when}`), ); expect(document.querySelector(".settings")!.textContent).not.toContain("Сначала привяжите Телеграм"); }); }); describe("Requirement: Кнопки Телеграма объяснены (FRTVL-24)", () => { 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($("mock-confirm").hidden).toBe(false)); expect($("unlink-button").hidden).toBe(true); expect($("telegram-action-hint").textContent).toBe( "«Подтвердить привязку» проверит, что бот получил код, и включит уведомления в этом чате.", ); expect($("mock-confirm").getAttribute("aria-describedby")).toBe("telegram-action-hint"); }); it("Scenario: Привязан", async () => { api.settings = { ...api.settings, linked: true, telegram: "telegram" }; await loadPage(); await vi.waitFor(() => expect($("unlink-button").hidden).toBe(false)); expect($("mock-confirm").hidden).toBe(true); expect($("telegram-action-hint").textContent).toBe( "«Отвязать» отключит этот чат: новые стажировки перестанут приходить в Телеграм.", ); }); it("Scenario: Не привязан", async () => { await loadPage(); await vi.waitFor(() => expect($("telegram-status").textContent).toBe("Телеграм не привязан")); expect($("mock-confirm").hidden).toBe(true); expect($("unlink-button").hidden).toBe(true); expect($("telegram-action-hint").textContent).toBe(""); }); });