Open MercatoDocsSearch docsAPI reference

Tutorials

Tutorial - testing modules

Choose a unit test for behavior inside one module and an integration test when the result depends on the running app or database. The examples show how to organize and run both.

This guide shows how to write and run unit tests for Open Mercato using Jest + ts-jest. It covers services, API handlers, and utilities, and explains how to keep tests out of the runtime bundle.

Prerequisites

Running Tests

Jest Aliases (in tests)

See jest.config.cjs: moduleNameMapper for the full mapping.

Patterns

1) Services (no DB)

Keep service tests fast by stubbing the EM (or other gateways) with minimal methods.

// packages/core/src/modules/auth/services/__tests__/authService.test.ts
import { AuthService } from '@open-mercato/core/modules/auth/services/authService'

describe('AuthService', () => {
  it('hashes password on create', async () => {
    const em: any = {
      calls: [],
      persist: (e: any) => {
        em.calls.push(['persist', e])
        return { flush: async () => em.calls.push(['flush']) }
      },
    }
    const svc = new AuthService(em)
    await svc.createUser({ email: '[email protected]', password: '<password>' } as any)
    expect(em.calls[0][0]).toBe('persist')
  })
})

Tips:

2) API Handlers (mock DI)

Import handlers and call them directly. Mock the DI container so handlers get fake services.

// packages/core/src/modules/auth/api/__tests__/login.test.ts
import { POST } from '@open-mercato/core/modules/auth/api/login'

jest.mock('@/lib/di/container', () => ({
  createRequestContainer: async () => ({
    resolve: () => ({
      findUserByEmail: async () => ({ id: 1, email: '[email protected]', passwordHash: 'hash', tenant: { id: 1 }, organization: { id: 1 } }),
      verifyPassword: async () => true,
      issueSession: async () => ({ token: '<token>' }),
    }),
  }),
}))

function makeRequest(body: any) {
  return new Request('http://localhost/api/auth/login', {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
  })
}

describe('auth login', () => {
  it('returns 200 for valid credentials', async () => {
    const res = await POST(makeRequest({ email: '[email protected]', password: '<password>' }))
    expect(res.status).toBe(200)
  })
})

Tips:

3) Utilities

Plain utilities are simple to test:

import { someUtil } from '@open-mercato/shared/lib/utils'

test('someUtil', () => {
  expect(someUtil('x')).toBe('X')
})

File Layout and Discovery

Keeping Tests Out of Runtime

Our module generator explicitly ignores tests so dev/runtime doesn’t import them:

If you introduce new patterns, ensure they don’t live under module api/ unless named with .test.ts.

Mutation Testing

Coverage says a line was executed. It does not say the test would notice if that line were wrong. Mutation testing closes that gap: StrykerJS rewrites your source (flipping < to <=, && to ||, removing a return) and reports every mutant the test suite failed to catch.

The gate is diff-scoped and advisory. Only the business-logic files your pull request changes are mutated, only in allowlisted packages, and a low score never blocks a merge – it produces a shortlist of behaviour worth a second look.

Enforcement exists in the code but is switched off, and turning it on is a core-team decision that has not been taken. Until it is, the mutation check is not part of the merge gate and is not a required check: read it, act on what it finds, and merge on the strength of the normal CI gate.

Only packages/shared is currently in scope. packages/core was measured and excluded – its command and validator layers sit under suites large enough that a single file's run was projected at several hours.

Run it locally against your own changes:

yarn mutation:changed

The run mutates real files on disk (Stryker's sandbox is incompatible with our per-package Jest configs), so it refuses to start on a dirty working tree. If a run is ever killed mid-flight, git checkout -- . restores everything.

Running the CI workflow on demand

Because the gate is diff-scoped, the CI job only runs when a pull request happens to touch an in-scope file – which makes it awkward to verify the workflow itself, or to debug a run that misbehaved. The Mutation tests workflow therefore accepts a manual dispatch:

gh workflow run mutation-tests.yml -f package=shared -f mutate=src/lib/boolean.ts

The selection is filtered by exactly the same allowlist, scope and path rules a diff-derived run uses, so a dispatch cannot mutate a package or a file the automatic path would have skipped.

A surviving mutant is a question, not a verdict

Three different findings look identical in the report, and only the first one means "write a test":

  1. A genuine coverage gap. The mutant changes behaviour and nothing fails. Add the missing assertion.
  2. An equivalent mutant. The mutant is behaviourally identical to the original, so no test could ever kill it. Suppress it (below).
  3. A redundant source path. Two checks guard the same condition, so each masks mutations of the other. The fix is in the source, not the tests.

Never chase the score by asserting exact log strings, error copy, or object shapes – the StringLiteral and Regex mutators are excluded precisely so that tactic earns nothing.

Suppressing an equivalent mutant

When – and only when – a mutant is genuinely unkillable, suppress it at the source. Every suppression MUST carry a one-line justification, and it is reviewed like any other code change:

// Stryker disable next-line BooleanLiteral: empty input is in neither value set, so both branches return null
if (!trimmed) return null

A suppression without a justification is a review blocker. If you cannot articulate why no test could kill the mutant, it is probably a coverage gap rather than an equivalent mutant.

Troubleshooting

Integration Testing (Playwright)

Use integration tests for full user flows and API scenarios that require a running app and real HTTP interactions.

What You Need to Start

Default test credentials come from initialization:

How to Create Integration Tests

  1. Create a new file in .ai/qa/tests/<category>/ named TC-<CATEGORY>-<NNN>.spec.ts.
  2. Use built-in helpers from .ai/qa/tests/helpers/:
    • UI auth helper: helpers/auth.ts (login(page, 'admin'))
    • API helper: helpers/api.ts
  3. Prefer Playwright semantic locators:
    • getByRole
    • getByLabel
    • getByText
    • getByPlaceholder
  4. Keep each test independent (login and setup inside the test or beforeEach).
  5. If a markdown scenario exists, keep it in .ai/qa/scenarios/TC-*.md and align steps with the spec.

Example skeleton:

import { test, expect } from '@playwright/test'
import { login } from '../helpers/auth'

test.describe('TC-ADMIN-999: Example flow', () => {
  test.beforeEach(async ({ page }) => {
    await login(page, 'admin')
  })

  test('completes the scenario', async ({ page }) => {
    await page.goto('/backend')
    await expect(page).toHaveURL(/\/backend/)
  })
})

How to Run Integration Tests

How to speed up ephemeral integration runs

yarn test:integration:ephemeral rebuilds and boots a fresh isolated environment on each run. That is reliable but slower for tight development loops.

Use full yarn test:integration:ephemeral for pre-merge validation and CI-like isolation.

For repeated local runs, prefer yarn test:integration:ephemeral:interactive to select tests from a menu and run them against one persisted ephemeral environment.

Notes

Previous: Tutorial - build your first Open Mercato app