# Vitest plugin

The options of `channelstack()` from `channelstack/vitest`, what the plugin adds to a Vitest run, and the fixtures it gives every test. For a walkthrough, see [Writing tests](https://channelstack.dev/docs/guide/writing-tests).

```ts title="vitest.config.ts"
import { defineConfig } from "vitest/config";
import channelstack from "channelstack/vitest";

export default defineConfig({
  plugins: [channelstack({ mode: "auto", timeout: "10s", quietFor: "750ms" })],
});
```

## Signature

```ts
import channelstack from "channelstack/vitest";

function channelstack(options?: ChannelstackIntegrationOptions): Plugin;
```

| Requirement | Value                                      |
| ----------- | ------------------------------------------ |
| Package     | `channelstack` (`npm i -D channelstack`)   |
| Import      | Default export of `channelstack/vitest`    |
| Vitest      | `>=5.0.0 <6` (an optional peer dependency) |
| Node        | `>=22`                                     |

## Options

```ts
interface ChannelstackIntegrationOptions {
  server?: string;
  mode?: "auto" | "attach" | "start";
  timeout?: Duration;
  quietFor?: Duration;
}
```

| Option     | Type                            | Default                                                  | Meaning                                                                                                                |
| ---------- | ------------------------------- | -------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `server`   | `string`                        | `CHANNELSTACK_URL`, else the URL in `<home>/server.json` | Attach to the server at this URL. Its token comes from `CHANNELSTACK_TOKEN`, or from `server.json` when the URLs match |
| `mode`     | `"auto" \| "attach" \| "start"` | `"auto"`                                                 | How the run finds its server. See [Modes](#modes)                                                                      |
| `timeout`  | `Duration`                      | `"10s"`                                                  | Default timeout of every matcher, of `channelstack.quiet()`, and of every SDK wait                                     |
| `quietFor` | `Duration`                      | `"750ms"`                                                | Default quiet window of negative and exact-count matchers, of `channelstack.quiet()`, and of the SDK's `latest…` reads |

A `Duration` is milliseconds as a number, or a string such as `"250ms"`, `"3s"`, `"1m"`.

`timeout` and `quietFor` are the defaults of the SDK's own waits too (`waitForReply`, `waitForComment`, `latestReply`, `settled`, …): the setup file sets them in every worker. A call that passes its own `timeout` or `quietFor` wins.

A project that sets no `testTimeout` gets one from the plugin: 30 seconds, or three times `timeout` if that's longer, so a failing check can report its own message before Vitest's 5-second limit stops the test. A project's own `testTimeout`, and Vitest's `--testTimeout` flag, always win.

## Modes

| Mode     | Server running                   | No server running                                                                                                                           |
| -------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `auto`   | Attaches to it                   | Starts a private one for the run                                                                                                            |
| `attach` | Attaches to it                   | Fails the run: ``No running channelstack server found. Start one with `npx channelstack`, or set CHANNELSTACK_URL and CHANNELSTACK_TOKEN.`` |
| `start`  | Ignores it, starts a private one | Starts a private one for the run                                                                                                            |

"Running" means a server at `server` (or `CHANNELSTACK_URL`, or the one in `server.json`) answers `GET /_channelstack/status` with the token within 2 seconds.

A private server is the binary of the installed platform package (`@channelstack/server-<platform>-<arch>`), or `CHANNELSTACK_SERVER_BIN`. It runs as `channelstack start --no-portless --port 0 --server-file <temporary file>`, so it uses a free loopback port, no `*.localhost` names, and never touches the shared `server.json`. It inherits the test run's environment, `CHANNELSTACK_<CHANNEL>_WEBHOOK_URL` and live credentials included. It has 15 seconds to become ready, and stops when the run ends.

## What the plugin adds

| Piece              | What it does                                                                                                                                                                                                                        |
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Global setup       | Runs once per run: attaches to or starts the server (by `mode`), and hands its URL, its token, `timeout` and `quietFor` to the test workers through Vitest's `provide`. Stops a server it started when the run ends                 |
| Setup file         | Runs in every worker, before the project's own `setupFiles`: one client per worker, one session per test, the fixtures below, the matchers registered with `expect.extend`, and `timeout` and `quietFor` as the SDK's wait defaults |
| Types              | Augments `vitest`: `TestContext` gets the fixtures, `Matchers` gets every [matcher](https://channelstack.dev/docs/reference/matchers), `ProvidedContext` gets `channelstack`                                                        |
| `test.env`         | Sets `CHANNELSTACK_VITEST_OPTIONS` to the plugin's options as JSON, for the global setup to read                                                                                                                                    |
| `test.testTimeout` | Set when the project sets none: 30 seconds, or three times `timeout`                                                                                                                                                                |

The setup file comes first in `setupFiles`, so its `beforeEach` work (opening the session, the fixtures) runs before the project's hooks, and its cleanup runs after them. A project's own hooks can use the fixtures.

The token goes to the workers directly. Nothing a test spawns inherits it.

## Sessions

Every test gets its own session in the server's shared world. The session opens before the test's hooks run and closes after them, whether or not the test names a fixture. Closing it removes everything the test created: people, channels, repositories, teams, pages, faults. Disposing never fails a test.

Relative fixture paths in a test (`files: "./fixtures/web"`, `content: { path: "./notes.md" }`) resolve from the test file's directory.

## Fixtures

Every fixture is automatic. Destructure what a test needs:

```ts title="TypeScript"
import { expect, test } from "vitest";

test("answers in the thread", async ({ slack, channelstack }) => {
  const ana = await slack.createUser({ name: "Ana" });
  const channel = await slack.createChannel({ participants: [ana, slack.app] });
  const msg = await ana.say("@my-agent hi", { channel });
  await expect(msg.thread).toHaveReplyFrom("my-agent");
  await channelstack.quiet();
});
```

```python title="Python"
from channelstack import SlackFixture
from pytest_channelstack import expect


async def test_answers_in_the_thread(slack: SlackFixture) -> None:
    ana = await slack.create_user(name="Ana")
    channel = await slack.create_channel(participants=[ana, slack.app])
    msg = await ana.say("@my-agent hi", channel=channel)
    await expect(msg.thread).to_have_reply_from("my-agent")
    # pytest-channelstack has no quiet() fixture: latest_reply waits until the agent is quiet.
    await msg.thread.latest_reply(from_="my-agent")
```

```rust title="Rust"
// Rust has no fixtures: the test opens its own session (see the SDKs page).
let session = fixtures::session().await?;
let slack = session.slack().await?;

let ana = slack.create_user().name("Ana").await?;
let channel = slack
    .create_channel()
    .participants(vec![&ana as &dyn Handle, &slack.app()])
    .await?;
let msg = ana.say("@my-agent hi").channel(&channel).await?;
expect(&msg.thread()).to_have_reply_from("my-agent").await?;
// latest_reply waits until the agent is quiet.
msg.thread().latest_reply().from("my-agent").await?;
```

| Fixture        | Type                  | What it is                                            |
| -------------- | --------------------- | ----------------------------------------------------- |
| `channelstack` | `ChannelstackFixture` | The server itself. See below                          |
| `slack`        | `SlackFixture`        | The test's view of the fake (or live) Slack workspace |
| `github`       | `GitHubFixture`       | The test's view of the GitHub organization            |
| `linear`       | `LinearFixture`       | The test's view of the Linear workspace               |
| `notion`       | `NotionFixture`       | The test's view of the Notion workspace               |
| `resend`       | `ResendFixture`       | The test's view of the Resend team                    |
| `google`       | `GoogleFixture`       | The test's view of the Gmail mailbox                  |
| `discord`      | `DiscordFixture`      | The test's view of the Discord guild                  |
| `openai`       | `OpenAIFixture`       | The fake OpenAI, your agent's model                   |

The channel fixtures' members are listed in the API reference: [`SlackFixture`](https://channelstack.dev/docs/reference/api/slack#slackfixture), [`GitHubFixture`](https://channelstack.dev/docs/reference/api/github#githubfixture), [`LinearFixture`](https://channelstack.dev/docs/reference/api/linear#linearfixture), [`NotionFixture`](https://channelstack.dev/docs/reference/api/notion#notionfixture), [`ResendFixture`](https://channelstack.dev/docs/reference/api/resend#resendfixture), [`GoogleFixture`](https://channelstack.dev/docs/reference/api/google#googlefixture), [`DiscordFixture`](https://channelstack.dev/docs/reference/api/discord#discordfixture), and the model's: [`OpenAIFixture`](https://channelstack.dev/docs/reference/api/openai#openaifixture).

A suite builds its own fixtures on these with `test.extend`:

```ts title="TypeScript"
import type { SlackConversation, SlackUser } from "channelstack";
import { test as base } from "vitest";

export const test = base.extend<{ ana: SlackUser; support: SlackConversation }>({
  ana: async ({ slack }, use) => use(await slack.createUser({ name: "Ana" })),
  support: async ({ slack, ana }, use) =>
    use(await slack.createChannel({ name: "support", participants: [ana, slack.app] })),
});
```

```python title="Python"
# conftest.py: pytest's own fixtures, built on channelstack's.
import pytest_asyncio

from channelstack import SlackConversation, SlackFixture, SlackUser


@pytest_asyncio.fixture(loop_scope="session")
async def ana(slack: SlackFixture) -> SlackUser:
    return await slack.create_user(name="Ana")


@pytest_asyncio.fixture(loop_scope="session")
async def support(slack: SlackFixture, ana: SlackUser) -> SlackConversation:
    return await slack.create_channel(name="support", participants=[ana, slack.app])
```

```rust title="Rust"
// Rust has no fixtures to extend: shared people and places are helpers each test calls.
pub async fn ana(slack: &SlackFixture) -> Result<SlackUser> {
    slack.create_user().name("Ana").await
}

pub async fn support(slack: &SlackFixture, ana: &SlackUser) -> Result<SlackConversation> {
    slack
        .create_channel()
        .name("support")
        .participants(vec![ana as &dyn Handle, &slack.app()])
        .await
}
```

### `ChannelstackFixture`

| Member  | Signature                                                                     | Returns                                               | Notes                                                                                                                                                                                                    |
| ------- | ----------------------------------------------------------------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `url`   | `readonly url: string`                                                        | `string`                                              | Control API and UI base, e.g. `https://channelstack.localhost`                                                                                                                                           |
| `env`   | `env(): Promise<Record<string, string>>`                                      | Env vars for the app                                  | What [`channelstack env`](https://channelstack.dev/docs/reference/cli#channelstack-env) prints: fake tokens, signing secrets, API URLs                                                                   |
| `quiet` | `quiet(options?: { quietFor?: Duration; timeout?: Duration }): Promise<void>` | Resolves when the app is quiet in this test's session | Quiet: no call in flight, no delivery in flight or about to be retried, no open stream, for `quietFor`. Defaults: the plugin's `quietFor` and `timeout`                                                  |
| `reset` | `reset(): Promise<void>`                                                      | `void`                                                | Drops all state on every channel, for every session. Avoid it in parallel suites. Refused with `unsupported_in_live` when a channel is live; that refusal fails the test, since it belongs to no session |

## Live refusals skip tests

When a channel runs live, some operations can't run there. The plugin turns two refusals into a skipped test, with the reason, instead of a failure:

| Error code            | Means                                                                                                                                                                                                                                                                                                                  | Outcome                         |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| `unsupported_in_live` | The operation has no live counterpart, or not yet (reading or forging a delivery, `uninstallApp`)                                                                                                                                                                                                                      | Test skipped: `live: <message>` |
| `action_requires`     | It needs a piece live mode doesn't drive yet, whatever the run has: the browser actor beyond typing and clicking ([#47](https://github.com/christian-bromann/channelstack/issues/47)), or proxy mode ([#24](https://github.com/christian-bromann/channelstack/issues/24)). Also a person with no saved browser session | Test skipped: `live: <message>` |
| Any other code        | `live_misconfigured`, `live_not_allowlisted`, `fake_actor_in_live_world`, a platform error, …                                                                                                                                                                                                                          | Test fails                      |

The skip is per test: the refused request names its session, so concurrent tests skip only themselves. A fake run never sees these refusals, so every test runs in full on every fake run.

A channel fixture that is refused while it is set up (its live backend isn't built, or its credentials are set in part) doesn't touch the other channels' tests. The refusal is kept and raised the first time the test uses that fixture: it skips the test for the two codes above and fails it for any other.

The matchers' failure messages add what the app left open ("Still open: …"). That read never turns a failing test into a skipped one.

See [Live mode](https://channelstack.dev/docs/guide/live-mode) and the [error codes](https://channelstack.dev/docs/reference/api/errors).
