End-to-End Testing with grammy-emulate (grammy-emulate )
Testing a grammY bot end-to-end has always been awkward. You either stub bot one method at a time, hand-craft Update objects for bot, or drive a real bot through a second Telegram account via Telethon. None of these exercise the full wire format, and none of them let you assert on multi-turn flows (edits, callbacks, follow-up messages) without fabricating state by hand.
The grammy plugin fills that gap. It boots a stateful, in-process Telegram Bot API emulator, points your grammY bot at it via the api option, and exposes a fluent surface for seeding fixtures, simulating user actions, and inspecting bot output. No real bot token, no network, no second Telegram account.
Built on @serejke/telegram-emulator
The underlying Bot API emulator is @serejke. It is a framework-agnostic HTTP server that speaks the real Bot API — this plugin just wires grammY’s Bot lifecycle to it and adds a test-facing ergonomic surface.
Installation
npm install --save-dev grammy-emulatePeer dependencies: grammy ^1 and, optionally, vitest ^1 for the custom matchers.
Quick Start
Here is a complete Vitest file that boots the emulator, seeds a bot and a user, mounts a grammY bot against it, sends a message, and asserts on the reply.
import { describe, expect, test } from "vitest";
import { Bot } from "grammy";
import { emulator } from "grammy-emulate";
import { emuVitest } from "grammy-emulate/vitest";
const emu = emulator();
emuVitest(emu);
describe("my bot", () => {
test("replies to /start", async () => {
const bot = await emu.seed.bot({ username: "my_bot" });
const alice = await emu.seed.user({ first_name: "Alice" });
const dm = await emu.seed.privateChat(bot, alice);
await emu.mount(bot, (token, apiRoot) => {
const b = new Bot(token, { client: { apiRoot } });
b.command("start", (ctx) => ctx.reply("hello"));
return b;
});
await emu.as(alice).in(dm).send("/start");
const reply = await emu.in(dm).waitForReply();
expect(reply).toMatchReply("hello");
});
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const { describe, test, expect } = require("vitest");
const { Bot } = require("grammy");
const { emulator } = require("grammy-emulate");
const { emuVitest } = require("grammy-emulate/vitest");
const emu = emulator();
emuVitest(emu);
describe("my bot", () => {
test("replies to /start", async () => {
const bot = await emu.seed.bot({ username: "my_bot" });
const alice = await emu.seed.user({ first_name: "Alice" });
const dm = await emu.seed.privateChat(bot, alice);
await emu.mount(bot, (token, apiRoot) => {
const b = new Bot(token, { client: { apiRoot } });
b.command("start", (ctx) => ctx.reply("hello"));
return b;
});
await emu.as(alice).in(dm).send("/start");
const reply = await emu.in(dm).waitForReply();
expect(reply).toMatchReply("hello");
});
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
emu wires the emulator into before (start), after (reset), and after (stop), so each test starts with a fresh store.
Seeding Fixtures
emu returns typed fixture builders for every chat shape real Telegram supports.
const bot = await emu.seed.bot({
username: "trip_bot",
commands: [{ command: "start", description: "Start" }],
});
const alice = await emu.seed.user({ first_name: "Alice", username: "alice" });
const bob = await emu.seed.user({ first_name: "Bob" });
const dm = await emu.seed.privateChat(bot, alice);
const group = await emu.seed.group({
title: "Test Group",
users: [alice, bob],
bots: [bot],
});
const sg = await emu.seed.supergroup({
title: "Community",
users: [alice, bob],
bots: [bot],
});
const topic = await emu.seed.forumTopic(sg, "general");
const channel = await emu.seed.channel({ title: "News", bots: [bot] });2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Private, group, supergroup (with forum topics), and channel chats are all modelled — including channel / edited semantics.
Mounting the grammY Bot
emu is the single point where your real grammY Bot meets the emulator. The factory receives the emulator-issued token and api; you construct the Bot, register its handlers, and return it. The helper calls bot, starts long-polling in the background, and resolves once polling is ready for traffic.
const mounted = await emu.mount(bot, (token, apiRoot) => {
const b = new Bot(token, { client: { apiRoot } });
b.command("start", (ctx) => ctx.reply("welcome"));
b.command("echo", (ctx) => ctx.reply(ctx.match?.toString() ?? ""));
return b;
});
// mounted.bot is the grammY Bot you built.
// mounted.stop() halts polling; emuVitest() also stops it between tests.2
3
4
5
6
7
8
9
Polling or Webhook
Pass mode: to exercise the same delivery path your production bot uses. The plugin stands up a receiver on a random free port, calls set on the emulator, and relies on grammY’s webhook to verify the X header on every incoming POST.
await emu.mount(bot, factory, {
mode: "webhook",
allowedUpdates: ["message", "callback_query"],
});2
3
4
Polling is the default. Both modes accept allowed.
Simulating User Actions
emu returns a fluent builder for every action a real Telegram user can take against your bot.
await emu.as(alice).in(dm).send("/start");
await emu.as(alice).in(dm).sendPhoto(photoBytes, { caption: "look" });
await emu.as(alice).in(dm).sendVideo(videoBytes, { duration: 10 });
await emu.as(alice).in(dm).sendAudio(audioBytes, { mimeType: "audio/mpeg" });
await emu.as(alice).in(dm).sendVoice(voiceBytes, { duration: 3 });
await emu.as(alice).in(dm).sendAnimation(gifBytes);
await emu.as(alice).in(dm).sendSticker(stickerBytes);
await emu.as(alice).in(dm).sendDocument(docBytes, { fileName: "notes.txt" });
await emu.as(alice).in(dm).edit(messageId, "edited text");
await emu.as(alice).in(dm).click(messageId, "menu:about");
await emu.as(alice).in(dm).react(messageId, "👍");
await emu.as(alice).in(dm).reply(otherMessageId, "on it");2
3
4
5
6
7
8
9
10
11
12
Every call dispatches a real Update through the emulator’s dispatcher to your mounted grammY bot.
Inspecting Bot Output
emu returns an inspector over the chat’s message stream.
await emu.in(dm).replies(); // bot-sent messages only
await emu.in(dm).messages(); // all messages (user + bot)
await emu.in(dm).lastReply();
await emu
.in(dm)
.waitForReply({ matcher: (m) => /welcome/i.test(m.text ?? "") });
await emu.in(dm).waitForReplyCount(3);
await emu.in(dm).drafts(draftId); // sendMessageDraft snapshots
await emu.inspect.callbackAnswer(callbackQueryId);2
3
4
5
6
7
8
9
10
wait polls the emulator’s store until a matching reply lands or a timeout elapses, so you never have to race the grammY poll loop by hand.
Injecting Faults
Testing error paths — retry logic, rate-limit handling, “bot blocked by user” branches — is where mock-based approaches fall over. The emulator exposes a typed fault-injection primitive that surfaces as emu in the plugin.
await emu.faults.inject({
bot,
method: "sendMessage",
code: 429,
retryAfter: 2,
count: 1,
});
await emu.as(alice).in(dm).send("/start");
// The bot's ctx.reply() throws a GrammyError(429); your bot.catch handler fires.2
3
4
5
6
7
8
9
10
The scoped during() sugar is cleared automatically on exit, even when the wrapped block throws.
await emu.faults.during(
async () => {
await emu.as(alice).in(dm).send("/start");
// assertions
},
{ bot, method: "sendMessage", code: 403 },
);2
3
4
5
6
7
Supported codes are 400, 401, 403, 404, and 429. count defaults to 1 — only the very next call fails.
Vitest Matchers
Importing grammy extends expect with bot-specific matchers.
expect(reply).toMatchReply("hello");
expect(reply).toMatchReply(/welcome/i);
expect(reply).toMatchReply({ text: "hello", reply_markup: undefined });
await expect(emu.in(dm)).toHaveReplied(/welcome/i);
await expect(emu.in(dm)).toHaveReplyCount(2);
await expect(answer).toHaveAnsweredCallback();2
3
4
5
6
7
The same inspector target passed to emu can be handed directly to the matchers.
What the Emulator Covers
Inherited from @serejke:
- Delivery:
getwithUpdates offsetconfirmation, long-poll takeover 409,setwithWebhook secretand 5xx retry,_token delete,Webhook get.Webhook Info - Messaging:
send,Message send,Photo send,Document send,Video send,Audio send,Voice send,Animation send,Sticker edit,Message Text edit,Message Reply Markup delete,Message send.Chat Action - Parse modes: MarkdownV2, HTML, and legacy Markdown, with UTF-16 entity offsets and real Telegram-style error wording on unescaped reserved characters.
- Callbacks and inline keyboards:
answerwithCallback Query text/show/_alert url/cacheround-trip._time - Reactions:
set, per-user and anonymous aggregate counts.Message Reaction - Chat types: private, group, supergroup (with forum topics and
message), channel (with_thread _id channeland_post edited)._channel _post - Forum topics: create, edit, close, reopen, delete.
- Privacy Mode: groups drop bare
/cmd;@botand_username /cmd@botpass through._username - Files:
getplusFile /filedownload; stable/bot<token> /. .. fileacross resends._id - Fault injection: 401 / 403 / 404 / 429 with
retryfor exercising adapter retry paths._after
The following are explicit non-goals for the underlying emulator: payments, games, Business API, Passport, inline mode, media groups (send), polls, and the legacy stories / web-apps surfaces. See the emulator’s non
Showcase
A production-shaped grammY bot with 22 end-to-end tests lives in the examples directory of the plugin repository. The same /echo hello test is also written in the classic transformer-mock style in bot so you can compare the two approaches side by side.