147 lines
7.2 KiB
TypeScript
147 lines
7.2 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
||
import { listApplications } from "../src/applications.js";
|
||
import { handleUpdate } from "../src/bot.js";
|
||
import { openDb } from "../src/db.js";
|
||
import { MockTelegramApi, pollUpdates, TelegramError, type TgUpdate } from "../src/telegram.js";
|
||
|
||
const USER = { id: 501, username: "aigerim", language_code: "ru" };
|
||
let uid = 0;
|
||
const msg = (text: string, from = USER): TgUpdate => ({ update_id: ++uid, message: { message_id: uid, chat: { id: from.id, type: "private" }, from, text } });
|
||
const btn = (data: string, from = USER): TgUpdate => ({
|
||
update_id: ++uid,
|
||
callback_query: { id: `cb${uid}`, from, data, message: { message_id: uid, chat: { id: from.id, type: "private" } } },
|
||
});
|
||
const contact = (phone: string, userId: number, from = USER): TgUpdate => ({
|
||
update_id: ++uid, message: { message_id: uid, chat: { id: from.id, type: "private" }, from, contact: { phone_number: phone, user_id: userId } },
|
||
});
|
||
|
||
function setup() {
|
||
const db = openDb();
|
||
const api = new MockTelegramApi();
|
||
const send = async (...us: TgUpdate[]) => { for (const u of us) await handleUpdate(db, api, u); };
|
||
const last = () => api.sent.at(-1)!.text;
|
||
return { db, api, send, last };
|
||
}
|
||
|
||
describe("internship-bot", () => {
|
||
it.each([
|
||
["almaty", "Алматы"], ["taldykorgan", "Алматы"], ["aktobe", "Актобе"], ["astana", "Астана"], ["kokshetau", "Астана"],
|
||
])("Scenario Outline: Маршрут города %s → офис %s", async (city, office) => {
|
||
const { send, last, api } = setup();
|
||
await send(msg("/start"));
|
||
const kb = api.sent[0]!.markup as { inline_keyboard: { callback_data: string }[][] };
|
||
expect(kb.inline_keyboard.map((r) => r[0]!.callback_data)).toContain(`city:${city}`);
|
||
await send(btn(`city:${city}`));
|
||
expect(last()).toContain("Оплачиваемая, 3 месяца");
|
||
expect(last()).toContain("Официальный договор");
|
||
expect(last()).toContain("Опыт не нужен");
|
||
expect(last()).toContain(`Офис набора: ${office}`);
|
||
});
|
||
|
||
it("Scenario: Неизвестный город", async () => {
|
||
const { send, last, db } = setup();
|
||
await send(msg("/start"), btn("city:paris"));
|
||
expect(last()).toContain("Такого города нет в списке");
|
||
expect(listApplications(db)).toHaveLength(0);
|
||
});
|
||
|
||
it("Scenario: Полный отклик", async () => {
|
||
const { send, last, db, api } = setup();
|
||
await send(msg("/start hh"), btn("city:kokshetau"), btn("apply"));
|
||
expect(last()).toContain("Их увидит только команда набора");
|
||
expect(last()).toContain("/delete");
|
||
await send(btn("consent:yes"), msg("Айгерим Сапарова"));
|
||
expect((api.sent.at(-1)!.markup as { keyboard: { request_contact?: boolean }[][] }).keyboard[0]![0]!.request_contact).toBe(true);
|
||
await send(msg("8 701 123 45 67"));
|
||
expect(last()).toContain("Рекрутер офиса Астана свяжется с вами");
|
||
expect(listApplications(db)).toMatchObject([
|
||
{ fullName: "Айгерим Сапарова", phone: "77011234567", city: "kokshetau", office: "astana", source: "hh", tgUsername: "aigerim" },
|
||
]);
|
||
});
|
||
|
||
it("Scenario: Полный отклик — свой контакт кнопкой", async () => {
|
||
const { send, db } = setup();
|
||
await send(msg("/start"), btn("city:aktobe"), btn("apply"), btn("consent:yes"), msg("Ерлан Ахметов"), contact("+77019998877", USER.id));
|
||
expect(listApplications(db)[0]).toMatchObject({ phone: "77019998877", office: "aktobe", source: "direct" });
|
||
});
|
||
|
||
it("Scenario: Отказ от согласия", async () => {
|
||
const { send, last, db } = setup();
|
||
await send(msg("/start"), btn("city:almaty"), btn("apply"), btn("consent:no"));
|
||
expect(last()).toContain("данные не сохранены");
|
||
await send(msg("Айгерим"));
|
||
expect(listApplications(db)).toHaveLength(0);
|
||
});
|
||
|
||
it("Scenario: Имя не запрашивается без согласия", async () => {
|
||
const { send, db } = setup();
|
||
await send(msg("/start"), btn("city:almaty"), btn("apply"), btn("consent:yes", { ...USER, id: 999 }));
|
||
await send(msg("Айгерим"), msg("87011234567"));
|
||
expect(listApplications(db)).toHaveLength(0);
|
||
});
|
||
|
||
it("Scenario: Неверный телефон", async () => {
|
||
const { send, last, db } = setup();
|
||
await send(msg("/start"), btn("city:almaty"), btn("apply"), btn("consent:yes"), msg("Айгерим"), msg("123"));
|
||
expect(last()).toContain("Номер не похож на телефон");
|
||
expect(listApplications(db)).toHaveLength(0);
|
||
});
|
||
|
||
it("Scenario: Чужой контакт", async () => {
|
||
const { send, last, db } = setup();
|
||
await send(msg("/start"), btn("city:almaty"), btn("apply"), btn("consent:yes"), msg("Айгерим"), contact("+77010000000", 777));
|
||
expect(last()).toContain("Это чужой контакт");
|
||
expect(listApplications(db)).toHaveLength(0);
|
||
});
|
||
|
||
it("Scenario: Удаление", async () => {
|
||
const { send, last, db } = setup();
|
||
await send(msg("/start"), btn("city:almaty"), btn("apply"), btn("consent:yes"), msg("Айгерим"), msg("87011234567"));
|
||
expect(listApplications(db)).toHaveLength(1);
|
||
await send(msg("/delete"));
|
||
expect(last()).toBe("Ваши данные удалены.");
|
||
expect(listApplications(db)).toHaveLength(0);
|
||
});
|
||
|
||
it("Scenario: Удаление без отклика", async () => {
|
||
const { send, last } = setup();
|
||
await send(msg("/delete"));
|
||
expect(last()).toBe("Сохранённых данных нет.");
|
||
});
|
||
|
||
it.each([["/start qsamruk", "qsamruk"], ["/start enbek", "enbek"], ["/start", "direct"], ["/start <b>x</b>", "direct"]])(
|
||
"Scenario Outline: Источник из ссылки «%s» → %s", async (command, source) => {
|
||
const { send, db } = setup();
|
||
await send(msg(command), btn("city:astana"), btn("apply"), btn("consent:yes"), msg("Айгерим"), msg("+7 701 123 45 67"));
|
||
expect(listApplications(db)[0]!.source).toBe(source);
|
||
});
|
||
|
||
it("язык кандидата: казахский", async () => {
|
||
const { send, last } = setup();
|
||
const kk = { ...USER, language_code: "kk" };
|
||
await send(msg("/start", kk), btn("city:taldykorgan", kk));
|
||
expect(last()).toContain("Қабылдау кеңсесі: Алматы");
|
||
});
|
||
|
||
it("групповые чаты игнорируются", async () => {
|
||
const { db, api } = setup();
|
||
await handleUpdate(db, api, { update_id: 1, message: { message_id: 1, chat: { id: -5, type: "group" }, from: USER, text: "/start" } });
|
||
expect(api.sent).toHaveLength(0);
|
||
});
|
||
|
||
it("Scenario: Конфликт опроса", async () => {
|
||
const api = new MockTelegramApi();
|
||
const ctl = new AbortController();
|
||
const seen: number[] = [];
|
||
const sleeps: number[] = [];
|
||
api.queue = [new TelegramError(409, "Conflict"), [{ update_id: 7, message: undefined }]];
|
||
await pollUpdates(api, {
|
||
signal: ctl.signal, log: () => {},
|
||
sleep: async (ms) => { sleeps.push(ms); },
|
||
onUpdate: async (u) => { seen.push(u.update_id); ctl.abort(); },
|
||
});
|
||
expect(sleeps).toEqual([30_000]);
|
||
expect(seen).toEqual([7]);
|
||
});
|
||
});
|