# Write Unit Tests for a Medusa Backend

Yes. An agent finds the custom code in a Medusa backend that no test covers, writes Jest unit tests where its config expects them, runs them and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/write-unit-tests/medusa/). 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 setup before it writes a test, because Medusa projects wire Jest in a particular way. In a Medusa backend like the one in medusajs/dtc-starter, `apps/backend/jest.config.js` transforms TypeScript with `@swc/jest`, loads `integration-tests/setup.js`, which clears MikroORM's `MetadataStorage`, and switches `testMatch` on `TEST_TYPE`: `integration:http` matches `integration-tests/http/*.spec.ts`, `integration:modules` matches `src/modules/*/__tests__/**`, and `unit` matches `src/**/__tests__/**/*.unit.spec.ts`. `package.json` has `test:unit`, `test:integration:http` and `test:integration:modules` scripts with `--runInBand --forceExit`, `@medusajs/test-utils` 2.22.2 beside `@medusajs/medusa` 2.22.2 and Jest 29, and no plain `test` script, so the root `turbo test` runs nothing in the backend. There is no `__tests__` directory anywhere under `src/`.

Then it finds the code worth testing: logic the project wrote, not framework it configured. `src/search/product.ts` defines the product search index with `defineSearchIndex`, a `productFields` schema, a `toDocument` function that trims and filters categories, tags and sales channels into a document, and a list of sixteen product events. Its helpers are pure functions: `toOptionValues` in `helpers/option-values.ts` flattens options into `Title:Value` strings and removes duplicates; `toProductPricing` in `helpers/pricing.ts` picks, per currency in `PRICE_CURRENCIES`, the cheapest variant's calculated and original amounts and the highest calculated amount, writes `on_sale` even when false, skips variants whose amount is not a number and writes nothing for a currency with no price; `resolveProductIds` in `helpers/resolve-product-ids.ts` maps an event to product ids, reading a variant's, option's or category's products through `query.graph` with `withDeleted` set for `.deleted` events, and pages through `query.search` in batches of 200 for a deleted sales channel. `src/lib/region-store-policies.ts` holds defaults, and `src/api/middlewares.ts` only calls `configureStoreSearch`, so neither needs a test.

The tests go where `test:unit` will find them. `src/search/helpers/__tests__/option-values.unit.spec.ts` covers an empty list, a null option, a title with surrounding whitespace, an empty value and the same value under two options. `pricing.unit.spec.ts` covers a product with no variants, one whose cheapest variant is not its original-price variant, a non-numeric amount, a missing `original_amount` falling back to the calculated one, an `on_sale` of false, and two currencies merged into one object, and tests `loadPricing` with a fake container whose `query.graph` records the context it was called with and returns rows per currency. `resolve-product-ids.unit.spec.ts` uses a fake `query` with `graph` and `search` functions: a product event returns its ids untouched, a `product-variant.deleted` event asks with `withDeleted: true`, a tag event flattens its products, a sales-channel event keeps paging until a page is shorter than 200, an unknown entity returns nothing. `toDocument` is not exported, so the agent exports it and adds `src/search/__tests__/product.unit.spec.ts` for the trimming and filtering, naming that one-line source change in the pull request. Every test is a table of inputs and expected outputs with no Medusa container, so the suite runs in seconds without a database.

The agent runs `pnpm install` with the repository's `pnpm@10.11.1` and `pnpm --filter @dtc/backend test:unit`, reads the pass and fail lines, and adds a `test` script to the backend's `package.json` that runs `test:unit`, so `turbo test` from the root covers it. It leaves `.github/workflows/update.yaml`, which only reacts to Medusa releases, alone, and notes in the pull request that a pull-request workflow running `turbo test` is a separate change.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Write unit tests for the custom code in this Medusa backend. Read apps/backend/jest.config.js, package.json, integration-tests/setup.js and everything under apps/backend/src first, and work out from testMatch exactly where unit tests must live and how they are named. Pick the project's own logic rather than framework configuration: the search index helpers, the document builder and anything else with branches. Write table-driven Jest tests with no Medusa container or database, using small fake query objects where a function reads through query.graph or query.search, and cover empty inputs, whitespace, duplicates, missing fields and pagination. If a function has to be exported to be tested, do that and say so. Install with the repository's package manager and run the backend's test:unit script; add a test script to the backend so turbo test runs it. Do not add a CI workflow. Open a pull request with the test output and a table of each function and what its cases cover.",
  "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 spec files under `__tests__` directories, the `export` on `toDocument`, and the `test` script line in `apps/backend/package.json`. Its description quotes the `test:unit` output from the run with each suite's name and pass count, and a table of every function tested with its cases, so a reviewer can see what the pricing and resolver logic is now held to.

A reviewer checks that the cases encode the behaviour the helpers' own comments describe, such as `on_sale` being written even when false and a missing price leaving a currency out, and that the fakes assert the arguments passed to `query.graph`, which is what the resolver tests are for. Merging gives the next change to `src/search` a suite that fails for the right reason.

## Run it on every nightly schedule

An automation in the Project that holds the repository takes a `schedule` trigger with `cron` set to a night-time hour in your `timezone`. Its runs are read-only, so the saved prompt asks the run to list the functions under `src/` with no spec file, write tests for the one with the most branches in a scratch copy, run them and answer with the diff and the result, which the console or `GET /o/{org}/sessions/{id}` shows in the morning. A run that should open the pull request is started from the team's own server with this body and a `request_id` that is a UUID v5 of the directory path it covers, so a retried start returns the run already started.

A backend with several custom modules gets one such run per module directory, each with its own `input` naming the path, so the search helpers and a loyalty module get separate pull requests.

## Why run it on Rush?

The decisions in this job come from reading: where `testMatch` says a file must live, which functions carry logic, what each comment promises, and what the fake for `query.graph` has to record. The agent does that in its own sandbox against the real tree, runs the suite with the project's own package manager, and keeps the full output in the run's record, so the pull request shows the tests passing rather than describing them.

The same run fits any Medusa 2 project: a backend with custom modules under `src/modules` whose tests belong in the `integration:modules` match, a plugin package, or a storefront's data layer. Each gets tests placed where its own config will find them and cases drawn from its own code.

## Frequently asked questions

### Why unit tests and not the integration suites Medusa offers?

`@medusajs/test-utils` can boot a container and a Postgres database for `integration:http` and `integration:modules` runs, which is right for API routes and modules with data models. The search helpers are pure functions, so unit tests cover them in seconds, and the pull request notes where an integration test would add value later.

### Does it change the code it tests?

Only to export `toDocument`, which the file keeps private today, so its trimming and filtering can be tested directly. The pull request calls out that one line; everything else in `src/search` is unchanged.

### Where do the test files have to live?

`jest.config.js` matches unit tests at `src/**/__tests__/**/*.unit.spec.ts` when `TEST_TYPE` is `unit`, which is what `test:unit` sets. A spec named or placed differently is silently skipped, which is why the run reads the config before writing a file.

### Will these run in CI?

The repository's only workflow reacts to Medusa releases, so not yet. The run adds a `test` script so `turbo test` covers the backend from the root, and the pull request says a pull-request workflow is the next step; a follow-up to the same session can add it.

## More Medusa jobs

- [Add Dependabot to a Medusa Monorepo](https://getrush.ai/run/add-dependabot/medusa/)
- [Add a Dev Container to a Medusa Monorepo](https://getrush.ai/run/add-dev-containers/medusa/)
- [Add a Dockerfile to a Medusa Backend](https://getrush.ai/run/add-dockerfile/medusa/)

## The same job on other stacks

- [Write Unit Tests for a Node.js App](https://getrush.ai/run/write-unit-tests/nodejs/)
- [Write Unit Tests for an Obsidian Plugin](https://getrush.ai/run/write-unit-tests/obsidian-plugin/)
- [Write Unit Tests for a Payload CMS App](https://getrush.ai/run/write-unit-tests/payload/)

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