126 lines
4.8 KiB
TypeScript
126 lines
4.8 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;
|
||
}
|
||
|
||
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/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.textContent);
|
||
|
||
beforeEach(() => {
|
||
api = { internships: cards, tokenRequired: false, token: "", running: false };
|
||
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("Неверный токен"));
|
||
});
|
||
});
|