freetravel/test/filters.test.ts
peppa-bot 67f04b1291
All checks were successful
peppa/lint lint: success за 3с
peppa/typecheck typecheck: success за 5с
peppa/test test: success за 3с
peppa/build build: success за 5с
ci / checks (pull_request) Successful in 1m3s
deploy / deploy (pull_request) Successful in 1m16s
FRTVL-29: логин бота целиком, «Открыть бота» только с рабочей ссылкой
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:57:36 +00:00

205 lines
12 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.

import { describe, expect, it } from "vitest";
import { applyFilters, botLabel, botLink, botProblem, 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(
"Стажировок пока нет. Введите код доступа и нажмите «Найти новые» — стажировки появятся в этом списке.",
);
});
it("Scenario: Пустой каталог без кода доступа", () => {
expect(emptyMessage(0, 0)).toBe(
"Стажировок пока нет. Код доступа здесь не нужен — нажмите «Найти новые», и стажировки появятся в этом списке.",
);
expect(emptyMessage(0, 0)).not.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)).toContain("Неверный код доступа");
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-19)", async () => {
const { missingTokenMessage, searchErrorMessage, telegramCodeHint } = await import("../public/filters.js");
it("Scenario: Неверный код при поиске — две фразы", () => {
expect(searchErrorMessage().split(". ")).toHaveLength(2);
});
it("Scenario: Поиск ничего не нашёл — сказано, что делать", async () => {
const { emptyMessage } = await import("../public/filters.js");
expect(emptyMessage(0, 0, false, { status: "ok", added: 0 })).toContain("ничего не нашёл");
expect(emptyMessage(0, 0, false, { status: "ok", added: 2 })).toContain("нажмите «Найти новые»");
});
it("Scenario: Пустой код — сообщение только когда код нужен", () => {
expect(missingTokenMessage(false, "", "telegram")).toBeNull();
expect(missingTokenMessage(true, "abc", "search")).toBeNull();
expect(missingTokenMessage(true, "", "search")).toContain("Введите код доступа");
expect(missingTokenMessage(true, "", "telegram")).toContain("настройки Телеграма не изменить");
});
it("Scenario: Подсказка Телеграма по шагам", () => {
expect(telegramCodeHint(false, "linked")).toBe("");
expect(telegramCodeHint(false, "pending")).toContain("только отправить боту");
expect(telegramCodeHint(true, "unlinked")).toContain("код доступа");
});
});
describe("Requirement: Логин бота целиком (FRTVL-29)", () => {
it("Scenario: Логин показан целиком, имя — отдельно", () => {
expect(botLabel({ botUsername: "peppa_bot" })).toBe("@peppa_bot");
expect(botLabel({ botUsername: "my_internships_bot", botName: "my_internships_bot" })).toBe("@my_internships_bot");
expect(botLabel({ botUsername: "nternships_bot", botName: "my_internships_bot" })).toBe(
"@nternships_bot (имя в Телеграме: my_internships_bot)",
);
});
it.each(["", "12345:AAAbbb-key", "@my_internships_bot", "bot", undefined])(
"Scenario Outline: Логин «%s» не задан или с ошибкой — понятное сообщение",
(login) => {
expect(botLabel({ botUsername: login as string })).toBe("бот ещё не настроен — владельцу нужно указать логин бота");
expect(botProblem({ telegram: "telegram", botUsername: login as string })).toBe("bad_login");
const tg = telegramState({ linked: false, telegram: "telegram", botUsername: login as string, telegramProblem: null });
expect(tg.ownerNote).toContain("логин бота не задан или задан с ошибкой");
expect(tg.unavailable).toBe("Уведомления временно недоступны.");
expect(tg.note).toBe("");
},
);
it("Scenario: Ссылка ведёт именно на этого бота", () => {
expect(botLink({ botUsername: "my_internships_bot", linkUrl: "https://t.me/my_internships_bot?start=abc" })).toBe(
"https://t.me/my_internships_bot?start=abc",
);
});
it.each([
["нет ссылки", { botUsername: "my_internships_bot", linkUrl: null }],
["нет логина", { botUsername: "", linkUrl: "https://t.me/?start=abc" }],
["другой бот", { botUsername: "my_internships_bot", linkUrl: "https://t.me/other_bot?start=abc" }],
["не Телеграм", { botUsername: "my_internships_bot", linkUrl: "https://evil.example/my_internships_bot" }],
["не адрес", { botUsername: "my_internships_bot", linkUrl: "t.me/my_internships_bot" }],
])("Scenario: Ссылку нельзя построить (%s) — кнопки нет", (_name, s) => {
expect(botLink(s)).toBe("");
});
it("Scenario: Проблема с ключом важнее логина", () => {
expect(botProblem({ telegram: "telegram", botUsername: "", telegramProblem: "bad_token" })).toBe("bad_token");
expect(botProblem({ telegram: "mock", botUsername: "" })).toBe(null);
});
});
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")).toContain("«Подтвердить привязку»");
expect(telegramActionHint("linked")).toContain("«Отвязать»");
});
});