# Write Vitest Tests for a Turborepo Monorepo

Yes. The agent adds Vitest to the packages that hold logic, a cached test task in turbo.json and a CI job, then opens a pull request with the tests passing.

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

## What the agent does

A monorepo with no tests needs two things at once: the tests, and a place for them in the task graph. In a Turborepo like t3-oss/create-t3-turbo, the root `package.json` pins `pnpm@10.19.0` and Node `^22.21.0`, and its scripts are `turbo run` calls: `build`, `lint`, `format`, `typecheck`. No package in the workspace has a `test` script, `turbo.json` has no `test` task, and `.github/workflows/ci.yml` runs three jobs, `lint`, `format` and `typecheck`. The logic worth testing is in `packages/api`: `src/trpc.ts` defines `publicProcedure` and a `protectedProcedure` that throws `UNAUTHORIZED` when the context has no session user, and `src/router/post.ts` has `all`, `byId`, `create` and `delete` over the Drizzle `Post` table from `packages/db/src/schema.ts`, where `CreatePostSchema` caps `title` and `content` at 256 characters.

The agent wires Vitest the way this workspace already shares its tools. Versions used by more than one package live in the `catalog:` block of `pnpm-workspace.yaml`, so `vitest` goes there, and `packages/api` gets `"vitest": "catalog:"` in its devDependencies with a `test` script of `vitest run`. In `turbo.json` it adds a `test` task that depends on `^topo`, the chain task `lint` and `typecheck` already use, so a change in `@acme/db` invalidates the cached test result of the package that imports it. A root `test` script calls `turbo run test`. Then `pnpm install` runs the root `postinstall`, which is `pnpm lint:ws`, a `sherif` pass over every manifest in the workspace, so a manifest it objects to stops the work before any test exists.

The tests call the router directly, with no HTTP server. `appRouter.createCaller` takes a context, and `createTRPCContext` shows its shape: `authApi`, `session` and `db`. With `session` set to `null`, `post.create`, `post.delete` and `auth.getSecretMessage` must each reject with `UNAUTHORIZED`, and `auth.getSession` must return `null`. With a session that carries a user, `getSecretMessage` returns its string, and a 257-character title sent to `post.create` is rejected as `BAD_REQUEST` before the database is touched. `CreatePostSchema` gets its own file: the two length caps, and that `id`, `createdAt` and `updatedAt` are not part of what it parses. One detail in `trpc.ts` would slow all of this down: `timingMiddleware` sleeps 100 to 500 ms per call when tRPC considers itself in development. The agent checks what that flag resolves to under Vitest and, if the delay is on, stubs the timer in the test setup instead of editing the middleware.

The four `post` procedures need a database. `packages/db/src/client.ts` builds its client from `@vercel/postgres`, and the `POSTGRES_URL` in `.env.example` is a hosted pooler address, so the agent points nothing at it. It installs PostgreSQL in its sandbox, builds a Drizzle client for that server inside the test setup with the same `schema` and `casing: "snake_case"` the real client uses, creates the tables from the schema and passes the client as `ctx.db`. The connection string comes from `TEST_DATABASE_URL`, which the agent lists under the `test` task's `env` in `turbo.json`: Turborepo hands a task only the variables its configuration names, and the `eslint-plugin-turbo` rules loaded in `tooling/eslint/base.ts` flag one that is read without being declared. The assertions follow the code: `all` returns at most 10 posts, ordered by `id` descending; `byId` returns no row for a uuid that is not there; `delete` removes exactly one. A fourth CI job, `test`, reuses the `./tooling/github/setup` composite action the other three share and adds a `postgres` service.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "This Turborepo monorepo has no tests. Read the root package.json, pnpm-workspace.yaml, turbo.json, .github/workflows/ci.yml, tooling/github/setup/action.yml, tooling/eslint/base.ts and every file under packages/api/src and packages/db/src first. Add Vitest to packages/api: put the version in the pnpm catalog, reference it with catalog: in the package, add a test script, a test task in turbo.json that depends on ^topo, and a root test script that runs turbo run test. Write tests that call appRouter.createCaller with a context you build: protected procedures reject with UNAUTHORIZED when session is null and work with a session user; input over the schema limits is rejected as BAD_REQUEST; CreatePostSchema is tested on its own. For post.all, post.byId, post.create and post.delete, install PostgreSQL in the sandbox, build a Drizzle client for it in the test setup with the same schema and snake_case casing, create the tables from the schema and pass it as ctx.db; do not connect to POSTGRES_URL. Read the connection string from TEST_DATABASE_URL and declare it under the test task's env in turbo.json. If the timing middleware delays calls under Vitest, stub the timer in test setup; do not change src/trpc.ts. Add a test job to ci.yml that uses the existing setup action and a postgres service. Run pnpm install, pnpm lint, pnpm lint:ws, pnpm format, pnpm typecheck and pnpm test until all pass, then run pnpm test again and confirm Turborepo reports a cache hit. Open a pull request that lists each test file, what it covers, and the output of every command.",
  "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

A pull request with four kinds of change. The manifests: one new line in the catalog of `pnpm-workspace.yaml`, a devDependency and a `test` script in `packages/api/package.json`, a root `test` script, and `pnpm-lock.yaml`. The task graph: a `test` entry in `turbo.json` with its `dependsOn` and `env`. The tests: files under `packages/api/src` for the auth boundary, the input limits, the schema and the four `post` procedures, plus the setup file that builds the test database client. And CI: a `test` job in `.github/workflows/ci.yml` beside the existing three.

The description pastes the output of `pnpm lint`, `pnpm lint:ws`, `pnpm format`, `pnpm typecheck` and `pnpm test` from the sandbox, and of the second `pnpm test`, where Turborepo's summary shows whether the task was replayed from cache. That second run is the proof the task is wired correctly: a test task that never hits the cache has an input it should not have, and one that hits it after a schema change is missing a dependency.

A reviewer checks three things before merging. That the tests assert behaviour the team wants to keep, since a test written from the code pins whatever the code does today. That `TEST_DATABASE_URL` is the only new variable and nothing in the diff reads `POSTGRES_URL`. And that the repository's own CI, now with four jobs, is green.

## Run it on every pull request that adds a package

New packages in this layout come from `turbo gen init`, whose template in `turbo/generators/templates/package.json.hbs` has `build`, `lint`, `format` and `typecheck` scripts and no `test`. An automation in the Project that holds the repository, with a `github` trigger on `pull_request.opened` and a prompt that asks for a `test` script and first tests for any package the pull request adds, starts one run per pull request. The trigger puts the pull request after the prompt and fills in nothing else, and it never fires for a pull request from a fork.

From your own server, the same body goes to `POST /o/{org}/sessions` once per repository, with a `request_id` that is a UUID v5 of the repository's full name so a retried call returns the run already started. A `webhook_url` set on the key receives `run.completed` with `session_url` for each run that key started.

## Why run it on Rush?

Adding tests to a monorepo is mostly setup that has to be proven by running it: a pnpm install that passes the workspace check, a database for the procedures that query one, four `turbo run` tasks that still pass, and a second test run to see the cache behave. The agent does that in its own sandbox, with Node from `.nvmrc`, pnpm from `packageManager` and a PostgreSQL it installed for the purpose, and every command with its output stays in the run's transcript at `GET /o/{org}/sessions/{id}/messages`.

Nothing in it needs the team's database or secrets. The run reads `.env.example` for the variable names, and the only connection string it uses points at the server inside its own sandbox. Several repositories can get the same treatment at once, each in a separate sandbox with its own branch and pull request.

## Frequently asked questions

### Why Vitest and not Jest?

The packages here are ESM TypeScript with `"module": "Preserve"` and bundler resolution in `tooling/typescript/base.json`, and one app already builds with Vite. Vitest runs that source without a separate transform setup. If your monorepo already has Jest in some packages, say so in the prompt and the agent extends what is there.

### Does every package get tests?

No. The agent adds a `test` script only where it writes tests, and Turborepo skips the task in packages that do not define it. In this layout that means `packages/api` first; `packages/validators` holds a single placeholder export and the tooling packages are configuration.

### Will the tests touch our real database?

No. They read `TEST_DATABASE_URL`, which points at PostgreSQL inside the sandbox during the run and at a service container in CI. The prompt forbids connecting to `POSTGRES_URL`, and a reviewer can confirm it by searching the diff for that name.

### What about the Expo and Next.js apps?

This run leaves them alone. Component and end-to-end tests need a browser or a simulator and their own configuration, and mixing them in would make the pull request hard to review. A follow-up run can add them once the `test` task exists.

## More Turborepo jobs

- [Add Remote Caching to a Turborepo Monorepo](https://getrush.ai/run/add-remote-caching/turborepo/)
- [Review Pull Requests on a Turborepo Monorepo](https://getrush.ai/run/review-pull-requests/turborepo/)
- [Make Turborepo CI Check Only the Packages a Pull Request Changed](https://getrush.ai/run/run-ci-on-changed-packages/turborepo/)

## The same job on other stacks

- [Write Vitest Tests for a Vite React App](https://getrush.ai/run/write-vitest-tests/vite-react/)
- [Write Vitest Tests for a Vue App](https://getrush.ai/run/write-vitest-tests/vue/)
- [Write Vitest Tests for a Zustand Store](https://getrush.ai/run/write-vitest-tests/zustand/)

## 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/)
