All checks were successful
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
197 lines
11 KiB
TypeScript
197 lines
11 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
||
import { applyFilters, botLabel, countriesOf, emptyMessage, isExample, linkCheckMessage, runSummary } from "../public/filters.js";
|
||
|
||
const cards = [
|
||
{ country: "Швейцария", language: "russian" },
|
||
{ country: "Турция", language: "russian" },
|
||
];
|
||
|
||
describe("Requirement: Фильтры", () => {
|
||
it("Scenario: Фильтр по стране", () => {
|
||
expect(applyFilters(cards, { country: "Турция" })).toEqual([{ country: "Турция", language: "russian" }]);
|
||
});
|
||
|
||
it("Scenario: Фильтр без совпадений", () => {
|
||
const shown = applyFilters(cards, { language: "not_required" });
|
||
expect(shown).toEqual([]);
|
||
expect(emptyMessage(cards.length, shown.length)).toBe("Нет стажировок под выбранные фильтры — выберите «Все» или другую страну");
|
||
});
|
||
|
||
it("без фильтров показывает всё, страны — по алфавиту", () => {
|
||
expect(applyFilters(cards, {})).toHaveLength(2);
|
||
expect(countriesOf(cards)).toEqual(["Турция", "Швейцария"]);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Список стажировок", () => {
|
||
it("Scenario: Пустой каталог у владельца", () => {
|
||
expect(emptyMessage(0, 0, true)).toBe("Стажировок пока нет. Нажмите «Найти новые» — стажировки появятся в этом списке.");
|
||
expect(emptyMessage(0, 0, true)).not.toMatch(/код доступа|Примеров/i);
|
||
});
|
||
|
||
it("Scenario: Пустой каталог без входа", () => {
|
||
expect(emptyMessage(0, 0)).toBe("Стажировок пока нет. Поиск запускает владелец сервиса — войдите, если это вы.");
|
||
});
|
||
|
||
it("Scenario: Поиск ничего не нашёл", () => {
|
||
expect(emptyMessage(0, 0, true, { status: "ok", added: 0 })).toBe(
|
||
"Ничего не найдено. Попробуйте запустить поиск позже — условия программ меняются.",
|
||
);
|
||
expect(emptyMessage(0, 0, true, { status: "error", added: 0 })).toContain("Стажировок пока нет");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Запуск поиска со страницы — отчёт", () => {
|
||
it("показывает итог запуска и ошибку", () => {
|
||
expect(runSummary({ status: "ok", found: 3, added: 2, rejected: 1 })).toBe("найдено: 3, новых: 2, отброшено: 1");
|
||
expect(runSummary({ status: "error", found: 0, added: 0, rejected: 0, error: "нет сети" })).toBe(
|
||
"Поиск завершился ошибкой: нет сети",
|
||
);
|
||
expect(runSummary(null)).toBe("ещё не запускался");
|
||
});
|
||
});
|
||
|
||
import { settingsErrorMessage, telegramDetail, telegramState } from "../public/filters.js";
|
||
|
||
describe("Requirement: Состояние Телеграма (FRTVL-8)", () => {
|
||
it("Scenario: три шага привязки", () => {
|
||
expect(telegramState({ linked: false }).step).toBe("unlinked");
|
||
expect(telegramState({ linked: false, linkUrl: "https://t.me/x" }).step).toBe("pending");
|
||
expect(telegramState({ linked: true }).status).toBe("Телеграм привязан");
|
||
});
|
||
|
||
it("Scenario: ошибки простыми словами", () => {
|
||
expect(settingsErrorMessage(401, undefined)).toBe("Вы не вошли или вход устарел. Войдите снова и повторите действие.");
|
||
expect(settingsErrorMessage(500, "boom")).not.toContain("boom");
|
||
expect(settingsErrorMessage(409, "Нет действующего кода привязки")).toContain("Нет действующего кода привязки");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Примеры помечены", () => {
|
||
it("Scenario: пример — источник на example.org, настоящая — нет", () => {
|
||
expect(isExample({ sourceUrl: "https://example.org/mock/a" })).toBe(true);
|
||
expect(isExample({ sourceUrl: "https://hotel.com/jobs" })).toBe(false);
|
||
expect(isExample({ sourceUrl: "не адрес" })).toBe(false);
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Бот не настроен (FRTVL-13)", () => {
|
||
it("Scenario: настоящий режим без имени бота — понятная подсказка", () => {
|
||
expect(telegramState({ linked: false, telegram: "telegram", botUsername: "" }).unavailable).toBe("Уведомления временно недоступны.");
|
||
expect(telegramState({ linked: false, telegram: "telegram", botUsername: "nternships_bot" }).note).toContain("Привязать Телеграм");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Понятная причина, почему бот не настроен (FRTVL-16)", () => {
|
||
it("Scenario: Ключ не дошёл до сервиса", () => {
|
||
const tg = telegramState({ linked: false, telegram: "mock", telegramProblem: "no_token" });
|
||
expect(tg.unavailable).toBe("Уведомления временно недоступны.");
|
||
expect(tg.detail).toContain("сервис не получил ключ Телеграм-бота");
|
||
expect(tg.detail).toContain("Нет TELEGRAM_BOT_TOKEN в окружении сервиса.");
|
||
});
|
||
|
||
it("Scenario: Ключ не подошёл", () => {
|
||
const tg = telegramState({ linked: false, telegram: "telegram", botUsername: "", telegramProblem: "bad_token" });
|
||
expect(tg.unavailable).toBe("Уведомления временно недоступны.");
|
||
expect(tg.detail).toContain("Телеграм не принял ключ бота");
|
||
expect(tg.detail).toContain("Телеграм не принял TELEGRAM_BOT_TOKEN (getMe).");
|
||
});
|
||
|
||
it("Scenario: Телеграм не принял ключ бота, хотя логин бота известен (FRTVL-30)", () => {
|
||
const tg = telegramState({ linked: false, telegram: "telegram", botUsername: "mock_bot", telegramProblem: "bad_token" });
|
||
expect(tg.unavailable).toBe("Уведомления временно недоступны.");
|
||
expect(tg.detail).toContain("Для владельца: Телеграм не принял ключ бота");
|
||
});
|
||
|
||
it("Scenario: владелец видит, что сделать (FRTVL-32)", () => {
|
||
expect(telegramState({ linked: false, telegram: "mock", telegramProblem: "no_token" }).ownerNote).toContain("добавьте ключ Телеграм-бота");
|
||
expect(telegramState({ linked: false, telegram: "telegram", botUsername: "x", telegramProblem: "bad_token" }).ownerNote).toContain("не принял ключ");
|
||
expect(telegramState({ linked: false, telegram: "telegram", botUsername: "nternships_bot", telegramProblem: null }).ownerNote).toBe("");
|
||
});
|
||
|
||
it("Scenario: Бот работает — подробностей нет", () => {
|
||
expect(telegramState({ linked: false, telegram: "telegram", botUsername: "nternships_bot", telegramProblem: null }).detail).toBe("");
|
||
expect(telegramDetail(undefined)).toBe("");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Вход владельца (FRTVL-47)", async () => {
|
||
const { accountView, runNextStep, runPeriod, runningMessage, searchLockedMessage, signInErrorMessage, telegramCodeHint } =
|
||
await import("../public/filters.js");
|
||
|
||
it("Scenario: Успешный вход — статус и кнопка выхода", () => {
|
||
expect(accountView({ signedIn: true, loginAvailable: true })).toEqual({
|
||
status: "Вы вошли как владелец сервиса.",
|
||
showSignIn: false,
|
||
showSignOut: true,
|
||
});
|
||
expect(searchLockedMessage(true)).toBe("");
|
||
});
|
||
|
||
it("Scenario: Неверный пароль — две фразы", () => {
|
||
expect(signInErrorMessage(401)).toBe("Пароль не подошёл. Проверьте его и попробуйте ещё раз.");
|
||
});
|
||
|
||
it("Scenario: Вход не настроен — кнопки «Войти» нет", () => {
|
||
const view = accountView({ signedIn: false, loginAvailable: false });
|
||
expect(view.status).toBe("Вход пока не настроен. Владелец сервиса должен задать пароль в настройках продукта.");
|
||
expect(view.showSignIn).toBe(false);
|
||
});
|
||
|
||
it("Scenario: Без входа — поиск недоступен с объяснением", () => {
|
||
expect(searchLockedMessage(false)).toBe("Запускать поиск может только владелец сервиса. Войдите, чтобы начать.");
|
||
expect(accountView({ signedIn: false, loginAvailable: true }).showSignIn).toBe(true);
|
||
});
|
||
|
||
it("Scenario: Поиск ещё не запускался — без кода доступа", () => {
|
||
expect(runNextStep(null, true)).toBe("Нажмите «Найти новые».");
|
||
expect(runNextStep(null, false)).toBe("");
|
||
});
|
||
|
||
it("Scenario: Поиск со страницы — начало и конец", () => {
|
||
const period = runPeriod({ startedAt: "2026-11-25T10:03:00", finishedAt: "2026-11-25T10:05:00" });
|
||
expect(period).toBe("начат 25.11.2026, 10:03, закончен 10:05");
|
||
expect(runPeriod(null)).toBe("");
|
||
expect(runningMessage(new Date("2026-11-25T10:03:00"))).toBe("Поиск начался в 10:03, идёт…");
|
||
});
|
||
|
||
it("Scenario: Подсказка Телеграма по шагам — без повторов и кода доступа", () => {
|
||
expect(telegramCodeHint()).toBe("");
|
||
});
|
||
});
|
||
|
||
describe("botLabel", () => {
|
||
it("показывает логин, а при другом имени — имя и логин", () => {
|
||
expect(botLabel({ botUsername: "peppa_bot" })).toBe("@peppa_bot");
|
||
expect(botLabel({ botUsername: "nternships_bot", botName: "my_internships_bot" })).toBe("my_internships_bot (@nternships_bot)");
|
||
});
|
||
it("без логина говорит, что бот не настроен", () => {
|
||
expect(botLabel({ botUsername: "" })).toBe("бот ещё не настроен");
|
||
});
|
||
});
|
||
|
||
describe("Requirement: Понятный итог подтверждения привязки", () => {
|
||
it("Scenario: Код устарел, неверный или не получен", () => {
|
||
expect(linkCheckMessage("not_started")).toContain("ещё не начата");
|
||
expect(linkCheckMessage("expired")).toContain("устарел");
|
||
expect(linkCheckMessage("wrong_code")).toContain("неверный");
|
||
expect(linkCheckMessage("not_received")).toContain("ещё не получил");
|
||
expect(linkCheckMessage("linked")).toBe("");
|
||
});
|
||
});
|
||
|
||
describe("FRTVL-24: подсказки галочки и кнопок Телеграма", () => {
|
||
it("enabledHint: без привязки — почему галочка недоступна, после — пусто", async () => {
|
||
const { enabledHint } = await import("../public/filters.js");
|
||
expect(enabledHint(false)).toBe("Сначала привяжите Телеграм, иначе присылать некуда.");
|
||
expect(enabledHint(true)).toBe("");
|
||
});
|
||
|
||
it("telegramActionHint: пояснение только к кнопке текущего шага", async () => {
|
||
const { telegramActionHint } = await import("../public/filters.js");
|
||
expect(telegramActionHint("unlinked")).toBe("");
|
||
expect(telegramActionHint("pending")).toBe("");
|
||
expect(telegramActionHint("linked")).toContain("«Отвязать»");
|
||
});
|
||
});
|