Docs menu

Guide

Writing tests

This page shows how to write channelstack tests in Vitest: the plugin, the fixtures each test gets, how people act, how the app gets access, and how tests clean up. It assumes the server and your app are running and connected, as in connecting your app.

Add the plugin#

npm i -D channelstack vitest
import channelstack from "channelstack/vitest";
import { defineConfig } from "vitest/config";

export default defineConfig({
  plugins: [channelstack()],
});

The plugin adds a global setup that finds the server, a setup file that gives each test its session and fixtures and registers the matchers on expect, and the types for both. You keep importing test and expect from vitest.

OptionDefaultWhat it does
mode"auto""attach" fails when no server is running. "start" always starts a private one. "auto" attaches if it can, and starts one otherwise
serverfrom ~/.channelstack/server.jsonThe server to attach to. Also CHANNELSTACK_URL, with CHANNELSTACK_TOKEN
timeout"10s"How long a matcher, channelstack.quiet() and every SDK wait (waitForReply, latestReply, settled, …) give up after. A project without its own testTimeout gets one above it: 30s, or three times timeout
quietFor"750ms"How long the app must be quiet before a negative or exact-count matcher checks, or a latest… read reads

Your app is configured from the server you started yourself (npx channelstack), so attaching to that server is the usual setup. A server the plugin starts on its own has no app connected to it. In CI, mode: "attach" makes a missing server fail at once instead of later. The plugin reference lists every option.

A first test#

import { expect, test } from "vitest";test("a mention gets exactly one reply, in the thread", async ({ slack }) => {  const ana = await slack.createUser({ name: "Ana" });  const channel = await slack.createChannel({ participants: [ana, slack.app] });  const msg = await ana.say("@my-agent summarize yesterday's incidents", { channel });  await expect(msg.thread).toHaveReplyFrom("my-agent", { text: /incident/i });  await expect(msg.thread).toHaveRepliesFrom(slack.app, { count: 1 });  await expect(channel).not.toHaveChannelMessageFrom("my-agent");});

The test creates a person and a channel, has the person mention the app, and checks three things a person would notice: there is an answer, there is only one, and it's in the thread rather than in the channel. Each matcher waits for the app; nothing in the test sleeps. The Python version runs under pytest; the Rust version opens its own session, since Rust's test harness has no fixtures (SDKs). The prose on this page names the TypeScript API.

The fixtures#

Every test gets these fixtures from its context:

FixtureWhat it is
slackThe fake Slack workspace: createUser, createChannel, the built-in app, calls, deliveries, fault
githubThe fake GitHub org: createUser, createRepo, the built-in app (a GitHub App)
linearThe fake Linear workspace: createUser, createTeam, the built-in app
notionThe fake Notion workspace: createUser, createPage, createDatabase, the built-in integration as app
resendThe fake Resend team: createUser (a mailbox outside it), the built-in team's address as app
googleThe fake Gmail mailbox: createUser (a mailbox outside it), the agent's own mailbox as app
discordThe fake guild: createUser, createChannel, the agent's bot as app, faults and verifyEndpoint
openaiThe fake OpenAI, your agent's model: respond (what the model answers), calls, latestCall, waitForCall, toolCalls, rateLimit. Not a platform: no people or app. See OpenAI
channelstackThe server itself: url, env() (what channelstack env prints), quiet() (resolves when the app is quiet in this test's session), reset()

The fixtures are scoped to the test's own session, which opens before the test's hooks and closes after them, whether the test names a fixture or not. Two tests that run at the same moment never see each other's people, channels, deliveries or model scripts.

Each fixture's app is the built-in app your code acts as on that platform, named my-agent. Matchers take it, or its name as a string, wherever they take an author: toHaveReplyFrom(slack.app) and toHaveReplyFrom("my-agent") mean the same. Every fixture also has createApp({ name }) and apps(), for a test that needs another app beside my-agent: a second agent, or a bot to talk to. A name in a matcher then means that app too (toHaveReplyFrom("coder")). See several apps.

People act, resources are read#

Every action is a method on the person who takes it. The content comes first, and where it happens is an option named after the resource:

await ana.say("@my-agent deploy web", { channel });await ben.click("Approve", { message: reply });await cara.comment("@my-agent fix this", { issue: pr });await dev.delegate(linear.app, { issue });await eve.reply("thanks!", { discussion });

The people of each platform have that platform's actions, and only those: a Slack user can say, reply, react, click and stop; a GitHub user can openIssue, openPullRequest, comment, review and push; a Linear user can createIssue, delegate, prompt and stop; a Notion user can comment, reply, edit and setProperty; a Resend or Google person can send, reply and read their inbox; a Discord user can say, reply, react, startThread, runCommand and click. A Slack user has no comment, so mixing them up is a type error. The platform pages list every action.

Every action resolves to what it created, so the next step needs no lookup. say gives you the message, with its thread, its conversation and the delivery it caused; comment on Linear gives you the comment and the agent session it opened.

Text is rich: @name becomes a real mention of that person or app on the platform (<@U…> in Slack, @login on GitHub, a mention node in Linear and Notion). Write @@ for a literal @.

Actions with no person behind them live on the fixture or the object they concern: slack.createChannel(…), repo.installApp(github.app), msg.delivery.retry(), modal.submit(…).

Give the app access explicitly#

Nothing grants your app access behind your back. Each platform's real rule applies, and you state the access in the test:

PlatformThe platform's ruleIn a test
SlackA bot gets events from, and can post in, only the channels it's a member of (not_in_channel otherwise)createChannel({ participants: [ana, slack.app] }), or later ana.invite(slack.app, { channel })
GitHubAn App gets webhooks only for repositories it's installed oncreateRepo({ apps: [github.app] }), or later repo.installApp(github.app)
NotionAn integration sees only pages connected to it, and their childrencreatePage({ connections: [notion.app] }), or later ana.connect(notion.app, { page })
LinearAn app is installed for the whole workspaceNothing to do
ResendA team gets only the mail sent to its own addressana.send({ to: [resend.app], … }); email between people never reaches it
GoogleA mailbox gets only the mail sent to it, and pushes only once the agent watches itana.send({ to: [google.app], … }); the agent calls users.watch itself
DiscordOnly the participants see a channel; the bot hears it only with discord.app among themdiscord.createChannel({ participants: [ana, discord.app] }), or ana.invite(discord.app, { channel })

Leaving the app out is how you test the uninvited case:

test("a channel the app isn't in stays silent until it's invited", async ({ slack }) => {  const ana = await slack.createUser({ name: "Ana", admin: true });  const channel = await slack.createChannel({ participants: [ana] });  const first = await ana.say("@my-agent are you here?", { channel });  await expect(first.thread).not.toHaveReplyFrom("my-agent");  await ana.invite(slack.app, { channel });  const second = await ana.say("@my-agent now?", { channel });  await expect(second.thread).toHaveReplyFrom("my-agent");});

On GitHub, Notion, Resend, Google and Discord, an action that reaches no app causes no delivery, so comment.delivery is undefined there.

Read what happened#

Resources are only read and waited on. For a check, use a matcher; when you need a value to work with, read it:

const msg = await ana.say("@my-agent what's the status of the web deploy?", { channel });await msg.thread.waitForReply({ from: "my-agent" });await ana.reply("and the API?", { thread: msg });const answer = await msg.thread.waitForReply({ from: "my-agent" });expect(answer.text).toMatch(/api/i);
To getUse
The next new message from someonethread.waitForReply({ from }), conversation.waitForMessage({ from }), issue.waitForComment({ from }), discussion.waitForComment({ from }), session.waitForActivity({ type })
The latest one, once the app is quietthread.latestReply({ from }), issue.latestComment({ from }), discussion.latestComment({ from })
Everything so farthread.replies(), conversation.messages(), issue.comments(), session.activities(), page.markdown()
What a person would readtranscript(), with toString() for snapshots
What the app calledslack.calls({ operation, error }), slack.waitForCall({ operation })
What the server sent the appmsg.delivery, github.deliveries({ type, resource })

Waiting and quiet explains how the waitFor… and latest… methods differ, and the API reference (Slack, GitHub, Linear, Notion, Resend, Google, Discord, OpenAI) lists every read.

Shared people with test.extend#

People and places you use in many tests belong in a fixtures file of your own (test/fixtures.ts, which the tests import test from). That's plain Vitest test.extend, built on channelstack's fixtures; in pytest it's fixtures in conftest.py, and in Rust, helper functions:

import type { SlackConversation, SlackUser } from "channelstack";import { expect, test as base } from "vitest";// In a project, this goes in test/fixtures.ts, exported, and the tests import `test` from there.const test = base.extend<{ ana: SlackUser; ben: SlackUser; support: SlackConversation }>({  ana: async ({ slack }, use) => use(await slack.createUser({ name: "Ana" })),  ben: async ({ slack }, use) => use(await slack.createUser({ name: "Ben", admin: true })),  support: async ({ slack, ana, ben }, use) =>    use(await slack.createChannel({ name: "support", participants: [ana, ben, slack.app] })),});test("an admin and a regular member see the same answer", async ({ support, ana, ben }) => {  const question = await ana.say("@my-agent who's on call?", { channel: support });  await ben.reply("+1, also need this", { thread: question });  await expect(question.thread).toHaveRepliesFrom("my-agent", { count: 1 });});

Each test still gets a fresh Ana, Ben and #support, because Vitest creates fixtures per test. The name support is unique per session, so parallel tests can all have their own #support. Fixtures compose: support depends on ana and ben.

People are never declared in a config file. Every test states the world it needs, and nothing is shared between tests by accident.

Fixed ids#

Generated ids are realistic and unique. When your app allowlists people by id, fix one:

test("allowlisted people by fixed id", async ({ slack }) => {  const admin = await slack.createUser({ name: "Cara", id: "U0ADMIN01" });  const stranger = await slack.createUser({ name: "Dev" });  const channel = await slack.createChannel({ participants: [admin, stranger, slack.app] });  const allowed = await admin.say("@my-agent rotate the API keys", { channel });  const refused = await stranger.say("@my-agent rotate the API keys", { channel });  await expect(allowed.thread).toHaveReplyFrom("my-agent", { text: /rotating/i });  await expect(refused.thread).toHaveReplyFrom("my-agent", { text: /not allowed/i });});

GitHub takes a numeric id, Linear and Notion take a UUID, and Discord a snowflake. The id must have the platform's format. A Resend or Google person's id is their address, so fix one with address.

A fixed id is unique in the whole world, not only in the test, because the app can't tell two U0ADMIN01 apart. While one session holds it, another session that asks for it is refused with invalid_argument, and the id is free again when the first session closes. Tests that fix the same id must not run at the same time.

Files and fixture directories#

A GitHub repository can start from a directory of files, and a Notion page from a Markdown file. Relative paths start from the test file, like an import. In Rust, which can't know where the test file is, they start from the working directory, which cargo test sets to the crate's directory (channelstack::runtime::files::set_files_root changes that):

const repo = await github.createRepo({  files: "./fixtures/web",  collaborators: [ana],  apps: [github.app],});const pr = await ana.openPullRequest(  {    from: "fix-login",    title: "Fix login redirect",    changes: { "src/login.ts": "export const redirect = '/home';\n" },  },  { repo },);const spec = await notion.createPage({  title: "Spec",  content: { path: "./fixtures/spec.md" },  connections: [notion.app],});

A Slack person shares files with a message the same way: ana.say("here's the log", { channel, files: [{ path: "./fixtures/crash.log" }] }), and the agent reads each from its url_private with the bot token.

files takes a directory path or a list of files. Each file is either inline, { name, content }, or on disk, { path }. changes on a pull request or a push maps paths to new contents, and null deletes a file.

Cleanup#

You don't clean up. When a test ends, the plugin closes its session, and closing removes everything the test created: people, channels, repositories, issues, pages. A fault the test injected is undone with it, and an app the test uninstalled is installed again. Cleanup never fails a test.

Inside a test, await using ends something early. A fault, for example, lasts until the end of its scope:

test("still answers when Slack refuses a message as too long", async ({ slack }) => {  const ana = await slack.createUser({ name: "Ana" });  const channel = await slack.createChannel({ participants: [ana, slack.app] });  await using _fault = await slack.fault({    type: "error",    operation: "chat.postMessage",    error: "msg_too_long",    times: 1,  });  const msg = await ana.say("@my-agent hello", { channel });  await expect(msg.thread).toHaveRepliesFrom("my-agent", { count: 1 });});

Outside Vitest, in a script or a beforeAll that needs its own scope, connect to the server and open a session yourself. Both are disposable:

import { connect } from "channelstack/client";await using client = await connect({ mode: "attach" });await using session = await client.openSession();const slack = await session.slack();const ana = await slack.createUser({ name: "Ana" });const msg = await ana.say("hi", { to: slack.app });const reply = await msg.thread.waitForReply({ from: "my-agent" });console.log(reply.text);// The session closes here, and removes Ana and the DM.

await using needs TypeScript 5.2 or later with the esnext.disposable lib, or a runtime that supports it natively.

Avoid channelstack.reset() in tests. It drops the whole world, including every other test's session, so it breaks a parallel suite. Fresh resources per test do the same job without the side effects.

Suggest changes to this page