# Write Japa Tests for an AdonisJS API

Yes. An agent reads an AdonisJS API's routes, validators and guard, writes Japa tests for signup, login, profile and logout plus a unit test, and opens a PR.

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

## What the agent does

The agent reads the test wiring that already exists, because an AdonisJS app ships a runner with no tests in it. In an API laid out like the `api` kit in adonisjs/starter-kits, `package.json` depends on `@adonisjs/core` `^7.5.2`, `@adonisjs/auth` `^10.1.0`, `@adonisjs/lucid` `^22.4.2`, `@adonisjs/session`, `@adonisjs/shield`, `@adonisjs/cors`, `@vinejs/vine` `^4.4.0` and `better-sqlite3`, with `@japa/runner` `^5.3.0`, `@japa/api-client` `^3.2.1`, `@japa/assert` and `@japa/plugin-adonisjs` for tests and `node ace test` as the `test` script. `adonisrc.ts` declares two suites, `unit` over `tests/unit/**/*.spec.ts` with a 2 second timeout and `functional` over `tests/functional/**/*.spec.ts` with 30 seconds. `tests/bootstrap.ts` registers `assert`, `pluginAdonisJS`, `dbAssertions`, `apiClient`, `sessionApiClient` and `authApiClient`, leaves `runnerHooks.setup` and `teardown` empty, and starts the HTTP server for the `functional` suite in `configureSuite`. `bin/test.ts` sets `NODE_ENV` to `test`, and `.env.test` sets only `SESSION_DRIVER=memory`. There is no file under `tests/unit` or `tests/functional`.

Then it reads what there is to test. `start/routes.ts` has `GET /` answering `{ hello: 'world' }` and an `/api/v1` group: `POST auth/signup` to `NewAccountController.store`, `POST auth/login` to `AccessTokensController.store`, and `GET account/profile` and `POST account/logout` behind the `auth` middleware. `app/validators/user.ts` builds `signupValidator` with a nullable `fullName`, an email that must be unique in `users.email`, a password of 8 to 32 characters and a `passwordConfirmation` that must equal it, and `loginValidator` with email and password. `app/models/user.ts` composes the generated `UserSchema` with `withAuthFinder(hash)`, so `User.verifyCredentials` does the password check, exposes `User.accessTokens` through `DbAccessTokensProvider`, and has an `initials` getter that takes the first letters of a two-word name, the first two letters of a single name, or the first two of the email's local part. `app/transformers/user_transformer.ts` picks `id`, `fullName`, `email`, `createdAt`, `updatedAt` and `initials`, so `password` never reaches a response. `config/auth.ts` makes the `api` tokens guard the default, `config/database.ts` points `better-sqlite3` at `tmp/db.sqlite3`, and `config/shield.ts` has CSRF off, so JSON posts in tests need no token.

The functional tests go one file per route group under `tests/functional/auth/` and `tests/functional/account/`. `runnerHooks.setup` gets `() => testUtils.db().migrate()` so the two migrations create `users` and `auth_access_tokens` before the suite, and each group uses `group.each.setup(() => testUtils.db().withGlobalTransaction())` so rows written by one test are rolled back before the next. `signup.spec.ts` posts a valid body with `client.post('/api/v1/auth/signup').json(...)`, asserts `200`, a `user` with `email` and `initials` and no `password` key, a non-empty `token`, and one row in `users` through `assert.dbRowCount`; posts the same email again and asserts `422` with the unique rule's message on `email`; posts a mismatched confirmation and asserts the `sameAs` error. `login.spec.ts` creates a user with `User.create`, logs in and asserts a token, then sends a wrong password and asserts the `E_INVALID_CREDENTIALS` response. `profile.spec.ts` uses `client.get('/api/v1/account/profile').loginAs(user)` from the auth plugin, which issues an access token for the default `api` guard, asserts the transformer's six fields, and asserts `401` without a token. `logout.spec.ts` logs in for a real token, posts to logout with it as a bearer header, asserts the message and that `auth_access_tokens` is empty, then reuses the token on the profile route and asserts `401`.

The unit test is `tests/unit/user.spec.ts` for the `initials` getter with the three cases the code handles: `Ada Lovelace` to `AL`, `Ada` to `AD`, and no name with `grace@example.com` to `GR`, built with `new User()` and no database. Every request body in the functional tests is typed through the generated routes registry that `tests/bootstrap.ts` declares, so a renamed route fails `pnpm typecheck` rather than a test at runtime. The agent runs `pnpm install`, `node ace migration:run` once to confirm the migrations apply to SQLite, `node ace test` for both suites and `pnpm typecheck` and `pnpm lint`, and keeps the Japa summary with each test's name.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Write Japa tests for this AdonisJS API, which has a configured runner but no tests. Read package.json, adonisrc.ts, tests/bootstrap.ts, bin/test.ts, .env.test, start/routes.ts, start/kernel.ts, app/controllers/new_account_controller.ts, app/controllers/access_tokens_controller.ts, app/controllers/profile_controller.ts, app/validators/user.ts, app/models/user.ts, app/transformers/user_transformer.ts, config/auth.ts, config/database.ts, config/shield.ts and the migrations first. Add a setup hook that runs migrations and a per-test global transaction. Write functional tests for signup including the duplicate email and mismatched confirmation cases, login including a wrong password, profile with loginAs and without a token, and logout including that the deleted token no longer authenticates, asserting response bodies against the transformer's fields and database rows with the db assertions plugin. Write a unit test for the User initials getter's three cases. Run migrations, node ace test, typecheck and lint, then open a pull request with the Japa summary.",
  "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

What comes back is a pull request that adds `tests/functional/auth/signup.spec.ts`, `tests/functional/auth/login.spec.ts`, `tests/functional/account/profile.spec.ts`, `tests/functional/account/logout.spec.ts` and `tests/unit/user.spec.ts`, and changes `tests/bootstrap.ts` for the migration hook. The description pastes the Japa summary with every test name under its suite, the `typecheck` and `lint` results, and a short table of which route each file covers and which error cases it asserts.

There is no workflow in this repository, so no check runs on the pull request; the run's record is the evidence, and it keeps the migration run, the test run and the two static checks in order. The pull request names the `add-github-actions-ci` job as the next step so the suite runs on every push.

Before merging, a reviewer decides whether the global transaction fits their database or whether `truncate()` per group is clearer, whether token expiry deserves a test once `config/auth.ts` sets one, and whether the `initials` cases should move into a transformer test as the app grows. The agent changes no controller, validator or route.

## Run it on every new AdonisJS service from the kit

A team that starts services from this kit starts one run per new repository from its own server: one `POST /o/{org}/sessions` with the repository in `resources` and a `request_id` that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own `start/routes.ts`, so a service that added a `web` session guard gets tests through `sessionApiClient` as well, and one that turned CSRF on in `config/shield.ts` gets the `withCsrfToken` call on each post.

After that, an automation in the Project with a `github` trigger on `pull_request.opened` and `pull_request.synchronize` and the prompt "if this pull request adds or changes a route in start/routes.ts, check that a functional test under tests/functional covers it and its validation errors, and say so in a comment" keeps the suite in step with the API. The trigger adds the pull request after the prompt and fires only for work by owners, members and collaborators.

## Why run it on Rush?

Tests for an API written without running them break on the framework's own rules: a functional suite that never ran `migrate()` fails on a missing `users` table, a `loginAs` on the wrong guard answers `401` where the test expects the profile, or a logout test that passes because it never checked the token row was deleted. The agent runs the migrations, the suites and the type check in its sandbox and reads the real Japa summary before it opens the pull request.

Every command stays with the run, from `pnpm install` to `pnpm lint`, and the pull request quotes them. Writing the first suite for a dozen services at once costs no more attention than one, because each run has its own machine, its own record and its own pull request.

## Frequently asked questions

### Why a global transaction per test instead of truncating tables?

`testUtils.db().withGlobalTransaction()` opens a transaction before each test and rolls it back after, so a test leaves no rows and the next one starts clean without a `DELETE` per table. It fits SQLite and PostgreSQL alike. `truncate()` is the alternative when a test needs to commit, and the pull request shows the one-line swap.

### Does loginAs really exercise the tokens guard?

Yes. The `authApiClient` plugin registered in `tests/bootstrap.ts` creates an access token for the user through the default guard, which `config/auth.ts` sets to `api`, and sends it as a bearer header. The logout test deliberately does not use it: it logs in for a real token so it can prove that token is deleted and refused afterwards.

### Will the tests pass once I switch from SQLite to PostgreSQL?

The suite reads `config/database.ts` through the app, so it runs against whatever connection `NODE_ENV=test` resolves to. The agent writes nothing SQLite-specific: migrations run through Lucid, assertions use `dbAssertions`, and the transaction hook is the same on both. A separate test database name in `.env.test` is the one thing to add for PostgreSQL.

### Why do the request bodies get type errors when I rename a route?

Because `tests/bootstrap.ts` extends Japa's `RoutesRegistry` with the registry that `@tuyau/core` generates under `.adonisjs/client`, so `client.post('/api/v1/auth/signup')` is checked against the real route list. A renamed route makes `pnpm typecheck` fail before any test runs, which is earlier than a `404` in a test would tell you.

## More AdonisJS jobs

- [Add Account Deletion to an AdonisJS API](https://getrush.ai/run/add-account-deletion/adonisjs/)
- [Add a Dockerfile to an AdonisJS App](https://getrush.ai/run/add-dockerfile/adonisjs/)
- [Add Email Verification to an AdonisJS App](https://getrush.ai/run/add-email-verification/adonisjs/)

## More jobs like this: Write the missing tests

- [Write Jest Tests for a React Native App](https://getrush.ai/run/write-jest-tests/react-native/)
- [Write Jest Unit Tests for a NestJS API](https://getrush.ai/run/write-jest-unit-tests/nestjs/)
- [Write Tests for a Ktor Server](https://getrush.ai/run/write-ktor-tests/ktor/)

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