Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 33 ยท Testing, Security and Production

Testing Modules, Workflows and APIs

Learn how to test a Medusa 2 backend: integration tests for HTTP routes, module integration tests, workflow tests, fixtures and step compensation checks.

A commerce backend moves money and stock, so "it seemed to work in the admin" is not a test strategy. Medusa ships test utilities that boot a real application against a real Postgres database, call your routes over HTTP and tear everything down again. Used well, a handful of tests cover the risky parts: your custom module, your workflows and the routes that expose them.

In this lesson you learn the three kinds of tests a Medusa project uses, how the test runners are wired into package.json, how to test a workflow and its compensation, and how to keep fixtures small. The real Jest code is read-only because it needs Postgres and the Medusa packages. Two runnable stand-ins show the ideas: testing a step's rollback, and replacing a service in a container with a fake.

Three kinds of tests

A project created with create-medusa-app is set up for Jest and distinguishes tests by a TEST_TYPE environment variable. The scripts in package.json look like this (read-only):

JSON
{
  "scripts": {
    "test:unit": "TEST_TYPE=unit NODE_OPTIONS=--experimental-vm-modules jest --silent --runInBand --forceExit",
    "test:integration:http": "TEST_TYPE=integration:http NODE_OPTIONS=--experimental-vm-modules jest --silent=false --runInBand --forceExit",
    "test:integration:modules": "TEST_TYPE=integration:modules NODE_OPTIONS=--experimental-vm-modules jest --silent --runInBand --forceExit"
  }
}

The file name decides which script picks a test up:

Kind Typical location What it proves
Unit src/**/__tests__/*.unit.spec.ts A pure function or helper, no database
Module integration src/modules/<name>/__tests__/*.spec.ts A custom module's service against a real database
HTTP integration integration-tests/http/*.spec.ts The whole app: routes, middlewares, workflows, modules

--runInBand runs test files one after another, because every integration test owns a database. Treat the exact flags as the template's current defaults; your project's own package.json is the source of truth.

flowchart LR
    U["Unit<br/>no database"] --> M["Module integration<br/>one module + Postgres"]
    M --> H["HTTP integration<br/>full app + Postgres"]

Wider tests prove more but run slower, so write many narrow ones and a few wide ones.

HTTP integration tests

medusaIntegrationTestRunner from @medusajs/test-utils creates a temporary database, runs migrations, starts the application and hands your suite helpers. A read-only example for a custom route:

TypeScript
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"

jest.setTimeout(60 * 1000)

medusaIntegrationTestRunner({
  inApp: true,
  env: {},
  testSuite: ({ api, getContainer }) => {
    describe("GET /store/reviews", () => {
      it("returns an empty list for a new product", async () => {
        const response = await api.get("/store/products/prod_123/reviews", {
          headers: { "x-publishable-api-key": "pk_test" },
        })

        expect(response.status).toEqual(200)
        expect(response.data.reviews).toEqual([])
      })
    })
  },
})

api is an Axios-style client already pointed at the test server. getContainer() returns the application container, so a test can resolve a module service to seed data or to check what a route wrote. Routes under /admin need an authenticated admin: projects typically add a small helper that creates an admin user and a token in beforeEach, and passes the header on every request. Keep that helper in one file so each test stays short.

Two habits keep these tests useful:

  • Assert on behavior, not on internals. Check the status code and the JSON a client sees; use the container only to arrange data or to confirm a side effect.
  • Test the failure paths. A request without the publishable key, an invalid body (the Zod validation from Custom API Routes and Middleware) and an unknown id should each have one test.

Module integration tests

When a module has real logic, test its service without the HTTP layer. moduleIntegrationTestRunner builds only that module, with its own migrations, against a throwaway database (read-only):

TypeScript
import { moduleIntegrationTestRunner } from "@medusajs/test-utils"
import { REVIEW_MODULE } from ".."
import ReviewModuleService from "../service"
import Review from "../models/review"

moduleIntegrationTestRunner<ReviewModuleService>({
  moduleName: REVIEW_MODULE,
  moduleModels: [Review],
  resolve: "./src/modules/review",
  testSuite: ({ service }) => {
    describe("ReviewModuleService", () => {
      it("creates a pending review", async () => {
        const review = await service.createReviews({
          product_id: "prod_1",
          rating: 5,
          status: "pending",
        })

        expect(review.status).toEqual("pending")
      })
    })
  },
})

The suite receives service, the instance of your module service with the auto-generated methods from Custom Modules and Data Models. Because only one module is loaded, the test is fast and cannot be broken by an unrelated module.

Testing workflows

A workflow is a function you can call with a container. In an HTTP or module-style integration suite you run it directly (read-only):

TypeScript
import { approveReviewWorkflow } from "../../src/workflows/approve-review"

it("approves a review", async () => {
  const container = getContainer()

  const { result } = await approveReviewWorkflow(container).run({
    input: { review_id: "rev_1" },
  })

  expect(result.status).toEqual("approved")
})

it("reports errors instead of throwing when asked", async () => {
  const { errors } = await approveReviewWorkflow(getContainer()).run({
    input: { review_id: "missing" },
    throwOnError: false,
  })

  expect(errors.length).toBeGreaterThan(0)
})

With throwOnError: false the call resolves and returns the collected errors, which makes failure tests easy to write. The important question for any multi-step workflow is: if step 3 fails, is the work of steps 1 and 2 undone? That is the compensation behavior from Compensation, Rollback and Long-Running Workflows. Test it by arranging a failure (a missing record, or a fake service that throws) and then asserting the earlier writes are gone.

Fixtures

Fixtures are the records a test needs before it can act. Rules that keep suites healthy:

  1. Create only what the test needs. A review test needs a product id, not a whole catalog with regions and shipping.
  2. Use small factory functions (makeReview({ rating: 1 })) instead of copying object literals.
  3. Do not share state between tests. Each integration test should start from a clean database; never rely on the order tests run in.
  4. Keep money as integers in fixtures, exactly like production data (Money as integers).

Stand-in 1: testing a step's compensation

The real runners need Postgres, so this stand-in reproduces the question a workflow test asks. A tiny saga runner executes steps and rolls back finished steps when a later one fails. The "tests" are plain assert checks run by a mini test harness, which prints a pass or fail line per test.

JS Does a failure roll back earlier steps?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second test is the valuable one: it proves that a failure leaves no half-finished state. The third is wrong on purpose so you can see what a failing assertion reports.

Stand-in 2: replacing a service with a fake

Because code resolves services from a container, a test can register a fake under the same key. This is how you test a workflow that normally calls a payment or email provider without calling it for real. Here a notification service is faked and the test checks what the code under test asked it to send.

JS A fake service in a container

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What to test first

You rarely need exhaustive coverage. Start with the code only you can break:

  1. Every custom workflow: success, and a failure that must roll back.
  2. Every custom route: auth required, validation errors, the happy path.
  3. Every custom module service method with branching logic (status transitions, limits).
  4. Subscribers that cause side effects, run twice with the same payload to confirm they are idempotent (Idempotency).

Do not re-test Medusa itself. The core team tests createProductsWorkflow; you test that your use of it is wired correctly.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which test kind boots the whole Medusa application against a real database and calls routes over HTTP?

    medusaIntegrationTestRunner creates a temporary database, runs migrations, starts the app and gives the suite an api client. Unit tests use no database, and module tests load only one module.
  2. 2. What does throwOnError false do when running a workflow in a test?

    With throwOnError false the run resolves and returns an errors array, which makes failure-path assertions simple. Compensation still runs.
  3. 3. Why do integration test scripts use --runInBand?

    Integration suites create and destroy databases, so running files in sequence avoids them interfering with one another.
  4. 4. Which test best protects against a half-finished order after a mid-workflow failure?

    Compensation exists to undo earlier steps. Forcing a failure and checking that earlier changes disappeared is the direct proof it works.
  5. 5. In the fake-service stand-in, why can a test replace the notification service?

    Dependency injection by key means the code under test never imports a concrete class, so tests register a fake with the same key.

Summary

  • Medusa projects have unit, module integration and HTTP integration tests, selected by TEST_TYPE and the file location.
  • medusaIntegrationTestRunner boots the app for route and workflow tests; moduleIntegrationTestRunner tests one module's service.
  • Run workflows with workflow(container).run({ input }), and use throwOnError: false to assert on failures.
  • Always test that a failing step triggers compensation of earlier steps.
  • Keep fixtures small and independent, and test your own wiring rather than Medusa's internals.
  • The runnable examples are stand-ins for the ideas; the Jest code needs Postgres and runs only in your project.

Next: Security and Performance