# Write Vitest Tests for a discord.js Bot

Yes. An agent adds Vitest tests for a discord.js bot's event handlers and services with mocked interactions, runs them with no bot token, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/write-vitest-tests/discord-js/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts with what the suite already covers. In a bot built on KevinNovak/Discord-Bot-TypeScript-Template, `package.json` runs `vitest run` for `npm test`, `vitest.config.ts` picks up `tests/**/*.test.ts` in the `node` environment, and nine test files exist: six for helpers under `src/utils` and three for the `/test`, View Date Sent and View Date Joined commands. Nothing touches `src/events`, where `CommandHandler`, `ButtonHandler`, `ReactionHandler` and `TriggerHandler` decide whether an interaction is answered at all, and nothing touches `src/services` or `src/jobs`. Those are the files the agent writes tests for.

It reuses the repository's own test kit instead of inventing one. `tests/builders/discord-builders.ts` already builds users, guilds, members, channels, messages and interactions with `mockDeep` from `vitest-mock-extended`, and `tests/helpers/test-utils.ts` has `mockProp` for read-only fields. The handlers branch on `instanceof ChatInputCommandInteraction` and `instanceof AutocompleteInteraction`, which a deep mock is not, so the agent uses the `asPrototype` helper at the bottom of the builders file and adds a button-interaction builder and a reaction builder beside the existing ones, in the same fluent style.

One obstacle comes before any assertion. Each handler loads `config/config.json` through a `require` made with `createRequire`, at import time, and `.gitignore` keeps every config file out of the repository except the `.example.json` ones. On a fresh clone, importing `command-handler.ts` throws before a test runs, and `vi.mock` does not intercept that kind of `require`. The agent adds a Vitest `globalSetup` file that copies `config.example.json`, `debug.example.json` and `bot-sites.example.json` to their real names only when those are missing, which is step one of the README's setup done for the test run, and registers it in `vitest.config.ts`.

Then it writes the cases from the code. For `CommandHandler`: a bot user and the client's own user are ignored; a command with a subcommand group resolves through `CommandUtils.findCommand` by its `names` array; an unknown command logs `commandNotFound` and answers nothing; autocomplete results are cut to `DiscordLimits.CHOICES_PER_AUTOCOMPLETE`; each `CommandDeferType` defers publicly, hidden or not at all; a command that throws sends the `errorEmbeds.command` embed and logs. With the example config's 10 commands per 30 seconds, the eleventh call from one user never reaches `execute`. `ButtonHandler` gets the `requireGuild` and `requireEmbedAuthorTag` paths, `TriggerHandler` the filter on `triggered(msg)`, and `ReactionHandler` the `requireSentByClient` check. The agent runs `npm test`, `npm run lint` and `npm run build` and fixes what its own files break.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Write Vitest tests for this discord.js bot's event handlers and services. Read package.json, vitest.config.ts, tsconfig.test.json, .gitignore, the README's setup steps, tests/builders/discord-builders.ts, tests/helpers/test-utils.ts and the existing tests first, and say what they cover and what they skip. Do not change anything under src. The handlers load config/config.json with createRequire at import time and that file is not in the repository: add a Vitest globalSetup that copies each config/*.example.json to its real name only when the real file is missing, and register it in vitest.config.ts. Reuse the existing builders, use asPrototype where a handler checks instanceof, and add builders for a button interaction and a message reaction in the same style. Cover CommandHandler (bots and self ignored, command lookup with subcommands, unknown command, autocomplete with the choice limit, each defer type, a failed defer, a command that throws, the rate limit from the example config), ButtonHandler, ReactionHandler, TriggerHandler, CommandRegistrationService with a stubbed REST client, and JobService. No test may need a bot token or reach the network. Where current behaviour looks wrong, write the test to the current behaviour and list it in the pull request; do not fix it. Run npm test, npm run test:coverage, npm run lint and npm run build, fix what your files break, and open a pull request with the output of all four.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

The pull request adds test files under `tests/events`, `tests/services` and `tests/jobs`, two new builders in `tests/builders/discord-builders.ts`, the setup file and one line in `vitest.config.ts`. It changes nothing under `src`. The description lists each handler with the branches now covered and pastes the output of `npm test`, `npm run test:coverage`, `npm run lint` and `npm run build` as the agent ran them, so the reviewer sees the suite's result and the coverage table without checking out the branch.

It also lists what the tests found and left alone. `ReactionHandler` takes its rate-limit slot under `msg.author.id`, the author of the message, while the checks around it are about the user who reacted. A test with two reactors on one message makes that visible; the agent writes it to the current behaviour, marks it in the description and does not change the handler. `vitest-mock-extended` sits under `dependencies`, not `devDependencies`, so it installs in production, and the agent says so and leaves the move to you. The repository has no workflow under `.github`, so nothing runs these tests on a pull request yet.

A reviewer checks three things: that no test needs a bot token or reaches Discord, that the setup file never overwrites an existing `config.json`, and that the assertions are about what the handler did (deferred, replied, called `execute`, logged) and not about how the mock was built.

## Run it on every merged pull request

A bot grows one command at a time, and each new command, button or trigger adds branches to the handlers. Create an automation in the Project that holds the repository with a `github` trigger on `pull_request.closed.merged` and your default branch in `branch_patterns`. The trigger puts the merged pull request after the saved prompt and fills in nothing, so the prompt is this page's request with one more sentence: write tests only for what that pull request added under `src`. It fires for owners, members and collaborators, never for forks or bots.

A team that runs several bots from the same template sends this body once per repository to `POST /o/{org}/sessions`, each with that repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a script that is run twice returns the runs it already started. An API key runs four at a time by default and the rest wait as `queued`, so the script needs no retry loop.

## Why run it on Rush?

Handler tests for a Discord bot are the ones nobody writes, because the setup is the hard part: a config file that is not in the repository, interactions that exist only as deep mocks, and class checks those mocks fail. On a laptop the suite passes because a real `config.json` with a real token is already sitting there. The agent's sandbox is a fresh clone with no token, so a test that passes there passes for the next contributor, and for CI when you add it.

The commands are real and their output is kept. The run's transcript holds every `npm test` invocation, including the failing ones along the way, so when the description says the eleventh call was rate limited you can read the assertion and the output that showed it. Your own checkout stays free while it works, and three bots get three runs at once, each in a separate sandbox.

## Frequently asked questions

### Does it need my bot token?

No. Every test builds its interaction from the builders in `tests/builders` and never opens a gateway connection or calls Discord's REST API. The copied example config holds the placeholder `<DISCORD_BOT_TOKEN>`, which is enough because nothing logs in.

### Will it change my handlers to make them testable?

Not unless you ask. The request says to leave `src` alone, so the agent works around the import-time config load with a setup file. Anything that looks wrong, such as the reaction limiter's key, is reported in the pull request and not fixed in it.

### Why not mock the config file with vi.mock?

`vi.mock` replaces modules loaded with `import`. The handlers read the JSON through `createRequire(import.meta.url)`, which Vitest does not intercept, so the mock would never apply. Supplying the file the code asks for is the smaller change.

### Does it test slash command registration?

It tests `CommandRegistrationService` against a stubbed `REST` client: which commands `view` lists as local only or remote only, and which ones `register` posts. It does not run `npm run commands:register`, which needs a real application id and token.

### Can it move the bot to strict TypeScript at the same time?

Keep that separate. `tsconfig.json` sets `strict` to false and the tests are written against the types as they are. Turning it on changes many files under `src`, which this request forbids, and it reviews better as its own pull request.

## More discord.js jobs

- [Write a Dockerfile for a discord.js Bot](https://getrush.ai/run/add-dockerfile/discord-js/)
- [Add Modals to a discord.js Bot](https://getrush.ai/run/add-modals/discord-js/)
- [Add a Slash Command to a discord.js Bot](https://getrush.ai/run/add-slash-command/discord-js/)

## The same job on other stacks

- [Write Vitest Tests for a Next.js App](https://getrush.ai/run/write-vitest-tests/nextjs/)
- [Write Vitest Tests for Pinia Stores](https://getrush.ai/run/write-vitest-tests/pinia/)
- [Write Vitest Tests for React Router Loaders and Actions](https://getrush.ai/run/write-vitest-tests/react-router/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
