Tutorials
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.
24.xjest.config.cjsyarn testyarn test:watch@/generated/* → generated/*@/lib/* → packages/shared/src/lib/*@/types/* → packages/shared/src/types/*@open-mercato/core/*, @open-mercato/cli/*, @open-mercato/shared/*, and other workspace packages@/* → apps/mercato/src/*See jest.config.cjs: moduleNameMapper for the full mapping.
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:
__tests__/helpers if reused.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:
Request with JSON bodies to simulate HTTP.Plain utilities are simple to test:
import { someUtil } from '@open-mercato/shared/lib/utils'
test('someUtil', () => {
expect(someUtil('x')).toBe('X')
})
__tests__ folders next to code.*.test.ts or *.test.tsxtestMatch: **/__tests__/**/*.test.(ts|tsx)Our module generator explicitly ignores tests so dev/runtime doesn’t import them:
__tests__ and __mocks__.test.ts, .spec.tsIf you introduce new patterns, ensure they don’t live under module api/ unless named with .test.ts.
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.
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.
Three different findings look identical in the report, and only the first one means "write a test":
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.
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.
yarn dev: means a test leaked into the runtime. Ensure tests are under __tests__ and the generator filters apply.jest.config.cjs and the file path.Use integration tests for full user flows and API scenarios that require a running app and real HTTP interactions.
24.xyarn installnpx playwright install chromiumyarn initializeyarn dev (or set BASE_URL to an already running instance)docker info must succeed)Default test credentials come from initialization:
[email protected] / secret[email protected] / secret[email protected] / secret.ai/qa/tests/<category>/ named TC-<CATEGORY>-<NNN>.spec.ts..ai/qa/tests/helpers/:
helpers/auth.ts (login(page, 'admin'))helpers/api.tsgetByRolegetByLabelgetByTextgetByPlaceholderbeforeEach)..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/)
})
})
yarn test:integrationnpx playwright test --config .ai/qa/tests/playwright.config.ts admin/npx playwright test --config .ai/qa/tests/playwright.config.ts admin/TC-ADMIN-002-api-key-revocation.spec.tsyarn test:integration:ephemeralyarn test:integration:ephemeral:interactiveyarn test:integration:reportyarn test:integration:ephemeral rebuilds and boots a fresh isolated environment on each run. That is reliable but slower for tight development loops.
yarn test:integration:ephemeral:interactive --no-screenshots.ai/qa/ephemeral-env.md (base_url)BASE_URL=http://127.0.0.1:<port> npx playwright test --config .ai/qa/tests/playwright.config.ts sales/TC-SALES-007.spec.ts --retries=0BASE_URL=http://127.0.0.1:<port> npx playwright test --config .ai/qa/tests/playwright.config.ts --workers=4 --retries=0yarn test:integration:ephemeral -- --filter sales/TC-SALES-007.spec.ts --no-screenshotsUse 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.
http://localhost:3000 and can be overridden with BASE_URL.5001 when available and writes the active URL to .ai/qa/ephemeral-env.md..ai/qa/tests/test-results/.PW_CAPTURE_SCREENSHOTS=1.