Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Patterns and Deployment

Testing Bots with Fakes

Test chat bots without a network: a recording fake API, injected clocks and random sources, update fixtures, testing webhook handlers and a node:test layout for your project.

Bots are hard to test by hand. To try a change you open a chat app, type a command, wait, and read the reply. You cannot easily check what happens at midnight, after a rate limit, or when 1,000 people press one button. Automated tests solve all of that, and chat bots are well suited to them because a bot is mostly a function from "an event" to "some API calls".

The recipe has four ingredients: pure-ish handlers, a fake API that records what the bot tried to send, injected time and randomness, and fixtures that look like real payloads. None of them needs a real token or network access.

Design for testability

Write handlers so that everything they touch comes in as an argument:

JavaScript
async function handleMessage({ update, api, db, now, random }) { /* ... */ }

A function that reaches for Date.now(), Math.random(), a global database and a global fetch is hard to test. A function that receives them is easy: tests pass fakes. This is dependency injection with no framework; the architecture lesson already used it (ctx.random, ctx.reply).

A recording fake API

Instead of calling api.telegram.org, the bot calls an api(method, params) function. In production it POSTs; in tests it records.

Node.js A fake API that records calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The fake lets you test the failure path (403) that is almost impossible to trigger by hand.

Fake time and randomness

Anything that depends on time is tested by moving a fake clock. Anything random is tested by supplying a function with a known answer. Keep the clock as a tiny object you can advance.

Node.js Testing a daily reward with a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

No waiting, no flakiness, and the "midnight" cases take microseconds.

A tiny test runner

Real projects use the built-in node:test runner. Its output includes timings, which vary from run to run, so here is the same idea as a hand-written mini runner that prints stable output. Study the structure: named tests, fresh fakes per test, assertions with node:assert.

Node.js A mini test suite for a command

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last test fails on purpose: the expectation is wrong (random() = 0 gives 1, not 2). Fix the expectation to see all six pass. Reading a failure message is half of what testing is about.

In your own project the same file looks like this with the real runner (read-only here, because node --test prints timings that change every run):

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

test("lowest possible roll is 1", async () => {
  const api = makeApi();
  await handleRoll({ update: upd("/roll 20"), api, random: () => 0 });
  assert.equal(api.calls[0].text, "d20: 1");
});

Run it with node --test. Add --watch while developing.

Testing the webhook layer

Handlers are only half of the story: the HTTP layer (secret check, body limit, 200 before work) deserves a few tests too. Start the server on port 0 (any free port) inside the test, send requests with fetch, then close it, exactly as in the Telegram webhook server lesson. Test the negative cases: missing secret, wrong secret, bad JSON, oversized body. For Discord interactions, generate a key pair in the test and sign payloads, as in the interactions lesson.

What to test, and what not to

Worth a test: parsing of commands and arguments, permission gates, cooldowns and escalation ladders, settings validation, database queries (against an in-memory SQLite), formatting of messages with tricky input, error paths such as blocked users.

Not worth testing against the real platform in CI: whether Telegram accepts your parse_mode. For that, keep a short manual or staging checklist, and one "smoke test" bot account used only in a private test chat.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why pass api, db, now and random into handlers instead of using globals?

    Injected dependencies are replaceable, which is what makes tests fast and deterministic.
  2. 2. What does a recording fake API give you?

    Tests assert on the recorded calls instead of on real network traffic.
  3. 3. How do you test a feature that happens 'after 24 hours'?

    An injected clock can jump ahead instantly.
  4. 4. Which case is most valuable to test with a fake that throws?

    Failure paths are rare in production and hard to trigger by hand, but easy with a fake.

Summary

  • Make handlers receive their dependencies so tests can fake them.
  • Record API calls in a fake and assert on them, including failure responses.
  • Use injected clocks and random sources for time-based and random behavior.
  • Test the HTTP layer on a free port with fetch, including rejection cases.
  • Use node --test in your project; keep a small manual checklist for platform behavior.

Next: Logging, monitoring and deployment