# Write the Missing Jest Tests for a Koa API

Yes. An agent finds the Koa modules your Jest suite skips, the logger, config, cron and routers, writes tests in your style and opens a PR with coverage figures.

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

## What the agent does

The agent runs the suite with coverage before it writes anything, so it is testing what is actually uncovered rather than what looks untested. In an API laid out like javieraviles/node-typescript-koa-rest, `package.json` runs Jest 26 with `ts-jest` on `**/tests/**/*.+(ts|tsx|js)` and has a `test:coverage` script; `tests/controller/user.test.ts` already has thirteen cases that mock `typeorm` and `class-validator` with `jest.mock` and drive every branch of `UserController`, and `tests/entity/user.test.ts` checks two properties on the entity. What the report shows as untouched is everything else under `src/`: the Winston middleware in `src/logger.ts`, `src/config.ts`, `src/cron.ts`, `src/controller/general.ts`, and the two router modules, while `src/server.ts` opens a TypeORM connection at import time and is left to the Postman collection in `integrationtests/`.

The logger middleware has the most logic. `logger(winston)` configures the transports from `config.debugLogging`, then returns a middleware that times `next()`, catches a thrown error and sets `ctx.status` from `err.status` or 500 with `err.message` as the body, and logs `GET /users 200 12ms` at `error` for a 5xx, `warn` for a 4xx and `info` otherwise. `tests/logger.test.ts` passes a fake Winston with `configure` and `log` spies, calls the middleware with a `ctx` of `method`, `originalUrl` and `status` and a `next` that resolves, rejects with a `status` of 404, or rejects with none, and asserts the level, the message format with a millisecond suffix, and the status and body set on the error paths.

`src/config.ts` reads `.env` at import, so `tests/config.test.ts` uses `jest.isolateModules` with `process.env` set per case: `PORT` unset gives 3000, `NODE_ENV=development` turns `debugLogging` on, `dbsslconn` off and points `dbEntitiesPath` at `src/entity/**/*.ts`, anything else points it at `dist/entity/**/*.js` with SSL on, and `cronJobExpression` is `0 * * * *`. `tests/cron.test.ts` mocks the `cron` package so `CronJob` is a spy, imports `src/cron.ts` and asserts it was constructed with that expression and a function. `tests/controller/general.test.ts` calls `helloWorld` with an empty context and checks the body. For the routers, `tests/routes.test.ts` imports `unprotectedRouter` and `protectedRouter` and asserts the registered methods and paths from each router's stack, which pins down the route table without a database.

The agent keeps the existing conventions: double quotes and semicolons from `.eslintrc`, `jest.mock` factories that stub the TypeORM and `koa-swagger-decorator` decorators the way `user.test.ts` does, and no new dependency, since `supertest` is not installed and the prompt forbids adding packages. It runs `npm run lint`, `npm test` and `npm run test:coverage` on Node 14, the version `engines` names, and pastes the coverage table before and after into the pull request. If a test shows a behaviour that looks wrong, such as the error path in `src/logger.ts` sending `err.message` to the client for a 500, it writes the test to the current behaviour and raises it in the description rather than changing production code.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Write the missing Jest tests for this Koa API. Read package.json, .eslintrc, tsconfig.json, src/server.ts, src/config.ts, src/logger.ts, src/cron.ts, src/controller/general.ts, src/controller/user.ts, src/unprotectedRoutes.ts, src/protectedRoutes.ts, tests/controller/user.test.ts and tests/entity/user.test.ts first, then run npm run test:coverage and keep the table. The user controller is already covered; write tests for the logger middleware (level per status range, the message format with milliseconds, and the catch path that sets status from err.status or 500 and the body from err.message), for config with jest.isolateModules and per-case process.env (PORT default, development versus other NODE_ENV for debugLogging, dbsslconn and dbEntitiesPath, the cron expression), for cron with the cron package mocked, for the general controller, and for the two routers' registered methods and paths. Use the existing style: jest.mock factories for decorators, double quotes, semicolons, no new dependency. Do not change production code; if a test reveals a bug, keep the test on current behaviour and say so. Run npm run lint, npm test and npm run test:coverage on Node 14 and open a pull request with the coverage before and after.",
  "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 `tests/logger.test.ts`, `tests/config.test.ts`, `tests/cron.test.ts`, `tests/controller/general.test.ts` and `tests/routes.test.ts`, and changes nothing under `src/`. Its description pastes the Jest summary, the `npm run lint` result and the two coverage tables, so the reviewer sees which files moved and that `src/server.ts` is still the one left to the integration suite.

Where a test pinned behaviour worth a second look, the description lists it as a question: the logger sends a thrown error's message to the client on a 500, and `getUser` answers 400 rather than 404 for a missing id, which the existing tests already assert. Neither is changed.

Before merging, a reviewer checks that the `jest.mock` factories match the decorators the modules import, decides whether the two questions become issues, and confirms the suite still runs on the Node version in `engines` and in `.github/workflows/ci.yml`, which installs Node 12 and is itself worth updating.

## Run it on every night

An automation with a `schedule` trigger, `cron` `0 2 * * *` and your `timezone`, runs this prompt in the Project's repository each night. The run reads the coverage table first, so once the modules above are covered the next night turns to whatever the week's commits left untested, and a night with nothing uncovered that unit tests can reach ends with a short note and no pull request.

Each night opens one pull request on its own branch with the before and after tables in its description. `max_runs_per_hour` on the automation keeps a mis-set schedule from starting more than one.

## Why run it on Rush?

The modules this suite skips are skipped for a reason: the logger needs a fake Winston, config reads `.env` at import and needs module isolation per case, cron needs its package mocked before import, and the routers pull in decorators that must be stubbed exactly as the controller tests stub them. Working that out is an afternoon on a laptop and is the reason the gaps stayed. The agent does it in its own sandbox on the project's Node 14, runs the suite and the coverage report, and the pull request carries both.

Every command and its output stays on the run, so the reviewer reads the coverage tables and the lint result without checking out the branch. Several services can be covered at once, each in its own sandbox, and a test that exposes a questionable behaviour is reported rather than quietly fixed.

## Frequently asked questions

### Why not test server.ts too?

`src/server.ts` calls `createConnection` to Postgres at import and starts the cron job and the listener inside its `then`, so importing it in Jest needs a database or a mock of all of TypeORM's connection setup. The repository already covers it end to end with the Newman collection in `integrationtests/`, so the pull request leaves it there and says so.

### How does it test config when it reads .env at import?

With `jest.isolateModules`, which gives each case a fresh module registry, and `process.env` set before the `require`. That lets one case see `NODE_ENV=development` and the next see nothing set, without the two leaking into each other, and without touching `src/config.ts`.

### Does it add supertest for the routers?

No. The prompt forbids new dependencies, and the router tests do not need one: `@koa/router` and `SwaggerRouter` expose their registered layers, so the test asserts the method and path table directly. A request-level test would also need the JWT middleware and a database, which is what the integration collection covers.

### What happens when a test finds a bug?

The test asserts what the code does today and the pull request raises it as a question. In this codebase the clear example is the logger's catch path, which sends `err.message` back as the response body even for a 500, and the user controller answering 400 for a missing id. Changing either is a product decision, not a side effect of adding tests.

### Which Node version does it run on?

Node 14, the version `engines` in `package.json` names and the `node:14-alpine` image uses. The description notes that `.github/workflows/ci.yml` still installs Node 12 on an `ubuntu-16.04` runner, so the workflow needs its own update before it can run the suite as the sandbox did.

## More Koa jobs

- [Add API Key Authentication to a Koa API](https://getrush.ai/run/add-api-key-auth/koa/)
- [Add Compression to a Koa App](https://getrush.ai/run/add-compression/koa/)
- [Add CORS to a Koa App](https://getrush.ai/run/add-cors/koa/)

## The same job on other stacks

- [Write Unit Tests for a LangChain.js App](https://getrush.ai/run/write-unit-tests/langchain/)
- [Write Unit Tests for a Laravel Project](https://getrush.ai/run/write-unit-tests/laravel/)
- [Write Unit Tests for an MCP Server](https://getrush.ai/run/write-unit-tests/mcp-server/)

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