Skip to content

Backend Testing Guide (PPP Instance) ​

This guide covers how to write and run backend tests in the PPP instance. There are two API packages, each with distinct testing patterns:

PackagePathPrimary test approach
backend-pppapi/backend-ppp/Service methods directly + Drizzle ORM
backend-coreapi/backend-core/testHandler utility + withTestData

Most PPP feature work lives in backend-ppp. Refer to the backend-core section when writing or modifying shared procedures in api/backend-core/.


Table of Contents ​

  1. Test Categorisation
  2. Running Tests
  3. Directory Structure
  4. backend-ppp: Test Patterns
  5. backend-core: Test Patterns
  6. Test Reliability: No Silent Skips
  7. Test Linting
  8. Common Mistakes to Avoid

Test Categorisation ​

Unit tests (*.test.ts) ​

Unit tests exercise isolated logic with no live database or network. They run with pnpm test (the default Vitest run) and must complete without TEST_DATABASE_URL being set.

  • Use in-process fakes or spy/mock utilities — never createInnerContext
  • Suitable for: pure functions, schema validators, utility helpers, middleware logic
  • File naming: <subject>.test.ts (co-located with the source file)

Integration tests (*.integration.test.ts) ​

Integration tests exercise a real PostgreSQL database and real service calls. They are excluded from pnpm test by convention and run separately:

bash
# From repo root — run exactly one integration file
pnpm test:backend-ppp:integration:file -- api/backend-ppp/src/services/myService/index.integration.test.ts
  • Require TEST_DATABASE_URL in the environment
  • Use createInnerContext({ cached: true, instanceId: 'pppDev' }) for context
  • Create isolated test data with IDs in the 999970–999998 reserved range (legacy) or via nextTestId() from ~ppp-api/utils/test-ids (preferred for new tests — avoids collision across parallel files)
  • Always clean up in afterAll

Quick reference ​

QuestionAnswer
Does my test need a real DB?*.integration.test.ts
Does my test only use in-memory logic?*.test.ts
Can pnpm test run without a database URL?Yes — unit tests only
Which runner executes integration tests?vitest.integration.file.config.ts (no global truncation)

The god-file rule ​

Test files exceeding 500 lines must be split into focused domain files. Each file runs on a separate Vitest worker, enabling parallel execution and faster CI feedback.

Split by concern, not alphabetically:

# Before (god file)
activitiesService.test.ts   ← 900 lines

# After (domain files)
activitiesService.crud.test.ts
activitiesService.search.test.ts
activitiesService.pagination.test.ts

The same rule applies to integration tests:

activitiesService.crud.integration.test.ts
activitiesService.search.integration.test.ts

Test ID range convention ​

Use IDs in the 999970–999998 range for legacy hardcoded IDs. For new tests, use nextTestId() instead — it starts at 1,000,001 to avoid collisions when multiple integration files run concurrently:

typescript
import { nextTestId } from '~ppp-api/utils/test-ids';

const userId = nextTestId(); // e.g. 1_000_001
const assessorId = nextTestId(); // e.g. 1_000_002

Running Tests ​

backend-ppp ​

bash
cd api/backend-ppp

# Run all tests
pnpm test

# Run a specific test file
pnpm test src/routers/procedures/activities/index.test.ts

# Run with verbose output
pnpm test --reporter=verbose src/routers/procedures/activities/index.test.ts

# Watch mode
pnpm test:watch

backend-ppp integration (single file, no global truncation) ​

Use the root command below to run exactly one integration test file.

bash
# From repo root
pnpm test:backend-ppp:integration:file -- api/backend-ppp/src/routers/procedures/relatedForm/index.integration.test.ts

Notes:

  • Loads environment from api/backend-ppp/.env
  • Requires TEST_DATABASE_URL to be set (the runner exits early if missing)
  • Forces NODE_ENV=test and runs PPP DB access against TEST_DATABASE_URL
  • Accepts exactly one file argument, and it must end with .integration.test.ts
  • Uses api/backend-ppp/vitest.integration.file.config.ts, which does not register global setup hooks that truncate all tables
  • Individual tests may still perform targeted cleanup/DELETE operations in their own hooks

Prepare a fresh/local test database before first run:

bash
pnpm db:ppp:migrate:url -- "$TEST_DATABASE_URL"

backend-core ​

bash
cd api/backend-core

# Run all tests
pnpm test

# Run a specific test file
pnpm test src/server/routers/core/procedures/searchContacts/index.test.ts

From the project root ​

bash
# Run all tests across all workspaces
pnpm test

Directory Structure ​

backend-ppp ​

api/backend-ppp/src/
├── routers/
│   └── procedures/
│       └── [domain]/
│           ├── index.ts             # Procedure implementation
│           └── index.test.ts        # Tests (co-located)
└── services/
    └── [ServiceName]/
        └── index.ts                 # Business logic (test this directly)

backend-core ​

api/backend-core/src/
├── server/
│   └── routers/
│       └── core/
│           └── procedures/
│               └── [feature]/
│                   ├── index.ts
│                   └── index.test.ts
└── services/
    └── core/
        └── [ServiceName]/

backend-ppp: Test Patterns ​

Integration Tests (Single File, No Global Truncation) ​

Use this mode when you want to debug integration behavior against a real PPP environment without running global table truncation:

bash
pnpm test:backend-ppp:integration:file -- api/backend-ppp/src/services/fhir/procedure.integration.test.ts

How it works:

  • Script entrypoint: package.json test:backend-ppp:integration:file
  • Runner script: scripts/run-backend-ppp-integration-file.mjs
  • Vitest config: api/backend-ppp/vitest.integration.file.config.ts
  • Safety behavior: no globalSetup/setupFiles, so no framework-level TRUNCATE ... CASCADE

Integration Test Conventions ​

The backend has two distinct test categories distinguished by file suffix:

CategoryFile suffixNetwork / DB?Run command
Unit*.test.tsNo — all I/O mockedpnpm test
Integration*.integration.test.tsYes — real PostgreSQLpnpm test:backend-ppp:integration:file

Rules:

  • Use *.integration.test.ts for tests that hit a real database or external service
  • Use *.test.ts for pure logic, mocked I/O, or anything that can run without TEST_DATABASE_URL
  • Run integration tests one file at a time while debugging to reduce blast radius and isolate failures
  • Keep explicit cleanup in afterAll for any records your test creates
  • If using a managed/remote DB, ensure TEST_DATABASE_URL is reachable from your machine and includes required SSL settings (for example sslmode=require)

Frontend has no integration test category. All frontend tests (instances/ppp/) are unit tests by convention. Tests requiring a live backend belong in the BDD E2E suite. See Frontend Testing — Test Categorisation for the full decision table.

Context Initialization ​

Always initialize context in beforeAll. Use instanceId: 'pppDev' for PPP backend tests.

typescript
import { createInnerContext } from '~ppp-core/server/context';
import { TrpcContext } from '~ppp-core/server/types';

let ctx: TrpcContext;

beforeAll(async () => {
  ctx = await createInnerContext({ cached: true, instanceId: 'pppDev' });
});

Note: backend-ppp uses 'pppDev', not 'mbDev'.


Database Setup with PppDb ​

PppDb provides a Drizzle ORM connection to the PPP PostgreSQL database. Use it directly for test setup and cleanup — unlike backend-core, it is fine to INSERT/UPDATE/DELETE in tests (you are setting up controlled test data).

typescript
import { PppDb } from '~ppp-api/utils/ppp-db';
import { activities, users, hospitals } from '@ppp-org/ppp/schema';
import { eq, inArray } from 'drizzle-orm';

const db = await new PppDb(ctx).getDb();

// Insert test data
await db.insert(hospitals).values(testHospital);
await db.insert(activities).values(activity);

// Delete test data
await db.delete(activities).where(eq(activities.id, activity.id));

Mock Data Utilities ​

Use the mock helpers from ~ppp-api/utils/mocking to create type-safe, realistic test objects. These do not write to the database — they create in-memory objects that you then insert yourself.

typescript
import {
  createMockUser,
  createMockActivity,
  createMockHospital,
} from '~ppp-api/utils/mocking';
import { createUserProfile } from '~ppp-api/services/userProfileService';

// Create mock objects (not yet in DB)
const user = createMockUser({ id: 999990 });
const assessor = createMockUser({ id: 999991 });
const activity = createMockActivity({ userId: user.id, assessorId: assessor.id });
const hospital = createMockHospital({ id: 999990 });

// Persist to DB
await createUserProfile(user, ctx); // Users go through the service
await db.insert(activities).values(activity);
await db.insert(hospitals).values(hospital);

Available mock generators:

FunctionCreates
createMockUser(overrides?)User with Faker data
createMockActivity(overrides?)Activity with relations
createMockHospital(overrides?)Hospital
createMockNotification(userId, overrides?)Notification
createMockCpdActivity(overrides?)CPD Activity
createMockPPP360(overrides?)PPP360 record
createDashboardTestData(ctx)Dashboard test data + cleanup fn

Test ID convention: Use IDs in the range 999970–999998 for legacy hardcoded IDs. For new tests, prefer nextTestId() from ~ppp-api/utils/test-ids to avoid collisions across parallel integration files. See Test Categorisation → Test ID range convention.


Testing Service Methods ​

The primary pattern in backend-ppp is to test service functions directly — not through tRPC procedures. Import the service and call it with test data and context.

typescript
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createInnerContext } from '~ppp-core/server/context';
import { TrpcContext } from '~ppp-core/server/types';
import { PppDb } from '~ppp-api/utils/ppp-db';
import { activities, users } from '@ppp-org/ppp/schema';
import { eq } from 'drizzle-orm';
import { createMockUser, createMockActivity } from '~ppp-api/utils/mocking';
import {
  getActivitiesByFilter,
  createActivity,
} from '~ppp-api/services/activitiesService';
import { createUserProfile } from '~ppp-api/services/userProfileService';

describe('activities', () => {
  let ctx: TrpcContext;
  const user = createMockUser({ id: 999990 });
  const assessor = createMockUser({ id: 999991 });
  const mockActivity = createMockActivity({ userId: user.id, assessorId: assessor.id });

  beforeAll(async () => {
    ctx = await createInnerContext({ cached: true, instanceId: 'pppDev' });
    const db = await new PppDb(ctx).getDb();

    // Clean up then create test users
    await db.delete(users).where(eq(users.id, user.id));
    await db.delete(users).where(eq(users.id, assessor.id));
    await createUserProfile(user, ctx);
    await createUserProfile(assessor, ctx);

    // Clean up then create test activity
    await db.delete(activities).where(eq(activities.id, mockActivity.id));
    await db.insert(activities).values(mockActivity);
  });

  afterAll(async () => {
    const db = await new PppDb(ctx).getDb();
    await db.delete(activities).where(eq(activities.id, mockActivity.id));
    await db.delete(users).where(eq(users.id, user.id));
    await db.delete(users).where(eq(users.id, assessor.id));
  });

  it('should return activities for a user', async () => {
    const result = await getActivitiesByFilter({ userId: user.id }, ctx);

    expect(result).toBeInstanceOf(Array);
    expect(result.length).toBeGreaterThan(0);

    result.forEach(activity => {
      expect(activity.userId).toBe(user.id);
    });
  });

  it('should create an activity', async () => {
    const input = {
      userId: user.id,
      assessorId: assessor.id,
      type: 'wba' as const,
      status: 'pending' as const,
    };

    const result = await createActivity(input, ctx);

    expect(result.id).toBeDefined();
    expect(result.userId).toBe(user.id);
    expect(result.type).toBe('wba');
  });
});

Testing via Router (testHandler) ​

For testing a procedure at the router level (verifying input/output handling and authorization), use testHandler from ~ppp-api/utils/tests. This wraps a router and returns a typed caller.

typescript
import { testHandler } from '~ppp-api/utils/tests';
import { timesheetRouter } from '../index';

it('should support admin view via procedure', async () => {
  const caller = testHandler(timesheetRouter);

  // Call procedure directly
  const adminResult = await caller.getByUserId({ userId: undefined });
  expect(adminResult).toBeInstanceOf(Array);
  expect(adminResult.length).toBeGreaterThanOrEqual(2);

  const userResult = await caller.getByUserId({ userId: user.id });
  expect(userResult).toBeInstanceOf(Array);
  userResult.forEach(t => expect(t.userId).toBe(user.id));
});

This is different from backend-core's testHandler — it accepts a router, not a config object.


Test Cleanup ​

Always clean up test data in afterAll. Track IDs you create so cleanup is comprehensive.

typescript
const testActivityIds: number[] = [];

// In test body — track what was created
const [created] = await db.insert(activities).values(activity).returning();
testActivityIds.push(created.id);

// In afterAll
afterAll(async () => {
  const db = await new PppDb(ctx).getDb();
  for (const id of testActivityIds) {
    await db.delete(activities).where(eq(activities.id, id));
  }
  // Clean up users and other dependencies too
  await db.delete(users).where(eq(users.id, testUser.id));
});

For batch deletes, use inArray when cleaning up multiple records:

typescript
import { inArray } from 'drizzle-orm';

await db.delete(activities).where(inArray(activities.id, testActivityIds));

backend-core: Test Patterns ​

Tests in backend-core use the testHandler utility with a config object, and withTestData for database fixtures.

Context initialization ​

typescript
import { createInnerContext } from '~ppp-core/server/context';

beforeAll(async () => {
  context = await createInnerContext({ cached: true, instanceId: 'mbDev' });
});

Test file header comment ​

Always include a run comment at the top:

typescript
/**
 * To run this test:
 * cd api/backend-core && pnpm test src/server/routers/core/procedures/searchContacts/index.test.ts
 */

testHandler (backend-core) ​

typescript
import { testHandler, identity } from '~ppp-core/utils/tests';

const res = await testHandler({
  module: 'core',
  op: 'searchContacts',
  type: 'query',
  identity, // default admin identity
  input: { searchText: 'Kelly' },
});

expect(res.items).toBeInstanceOf(Array);

withTestData (backend-core) ​

typescript
import { withTestData } from '~ppp-core/utils/tests';

const result = await withTestData(context, [
  {
    tableName: 'mb_user',
    records: [{ id: 'user-1', fullname: 'John Doe', email: 'john@example.com' }],
  },
]);

const { cleanup } = result;

afterAll(async () => {
  await cleanup();
});

For full backend-core testing documentation, see api/backend-core/CLAUDE.md and docs/backend/trpc-procedures.md in embrace-v2.


Test Reliability: No Silent Skips ​

Every assertion must execute in every test run.

Assertions inside conditional blocks that may not run create false confidence.

Anti-patterns to avoid ​

typescript
// ❌ NEVER: Assertion inside conditional
if (result.length > 0) {
  result.forEach(item => {
    expect(item.userId).toBe(user.id); // May never run!
  });
}

// ❌ NEVER: forEach without length assertion
result.forEach(item => {
  expect(item.type).toBe('wba'); // Runs 0 times if result is empty!
});

Correct patterns ​

typescript
// ✅ ALWAYS: Verify data exists first
expect(result).toBeInstanceOf(Array);
expect(result.length).toBeGreaterThan(0); // Ensure we actually have test data

result.forEach(item => {
  expect(item.userId).toBe(user.id); // Will always execute
});

// ✅ Be specific about counts
expect(result.length).toBe(1); // Exact count
expect(result[0].type).toBe('wba'); // Exact value

Test reliability checklist ​

  • [ ] No if blocks wrapping expect() calls
  • [ ] Array length asserted before forEach
  • [ ] No early return before all assertions complete
  • [ ] Specific assertions over vague .toBeDefined() where possible

Test Linting ​

Catch TypeScript errors in test files before running the full suite:

bash
# backend-ppp
cd api/backend-ppp && npx tsc --noEmit -p ./tsconfig.lint.json

# backend-core
cd api/backend-core && npx tsc --noEmit -p ./tsconfig.lint.json

Recommended workflow:

  1. Write test file
  2. Run typecheck — fix any type errors
  3. Run the test

Common Mistakes to Avoid ​

Using 'mbDev' instanceId in backend-ppp tests ​

typescript
// ❌ Wrong for backend-ppp
ctx = await createInnerContext({ cached: true, instanceId: 'mbDev' });

// ✅ Correct for backend-ppp
ctx = await createInnerContext({ cached: true, instanceId: 'pppDev' });

Using test IDs that conflict with real data ​

typescript
// ❌ Bad — small IDs may conflict with real records
const user = createMockUser({ id: 5 });

// ✅ Good — use the reserved high-ID range
const user = createMockUser({ id: 999990 });

Skipping cleanup ​

typescript
// ❌ Bad — test data persists, pollutes future runs
afterAll(async () => {
  // forgot to clean up!
});

// ✅ Good — track and delete everything created
afterAll(async () => {
  const db = await new PppDb(ctx).getDb();
  await db.delete(activities).where(inArray(activities.id, testActivityIds));
  await db.delete(users).where(eq(users.id, testUser.id));
});

Calling backend-ppp's testHandler like backend-core's ​

typescript
// ❌ Wrong — backend-core API, won't work in backend-ppp
const res = await testHandler({
  module: 'ppp',
  op: 'timesheets.getByUserId',
  type: 'query',
  identity,
  input: {},
});

// ✅ Correct for backend-ppp
const caller = testHandler(timesheetRouter);
const res = await caller.getByUserId({ userId: undefined });

Importing unused schemas or utilities ​

Only import what you actually use. Unused imports fail the TypeScript lint check.

typescript
// ❌ Bad — importing eq but not using it
import { eq, inArray } from 'drizzle-orm'; // inArray never used in this file

// ✅ Good
import { eq } from 'drizzle-orm';

Not cleaning up before inserting (causing duplicate key errors) ​

typescript
// ✅ Always delete before inserting test data with fixed IDs
await db.delete(users).where(eq(users.id, user.id));
await createUserProfile(user, ctx);

Complete backend-ppp Example ​

typescript
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { createInnerContext } from '~ppp-core/server/context';
import { TrpcContext } from '~ppp-core/server/types';
import { PppDb } from '~ppp-api/utils/ppp-db';
import { timesheets, users, hospitals } from '@ppp-org/ppp/schema';
import { eq } from 'drizzle-orm';
import { createMockUser, createMockHospital } from '~ppp-api/utils/mocking';
import {
  getTimesheetsByUserId,
  getAllTimesheets,
} from '~ppp-api/services/timesheetServices';
import { createUserProfile } from '~ppp-api/services/userProfileService';

describe('timesheets', () => {
  let ctx: TrpcContext;
  const user1 = createMockUser({ id: 999991 });
  const user2 = createMockUser({ id: 999992 });
  const testHospital = createMockHospital({ id: 999991 });
  const testTimesheetIds: number[] = [];

  beforeAll(async () => {
    ctx = await createInnerContext({ cached: true, instanceId: 'pppDev' });
    const db = await new PppDb(ctx).getDb();

    await createUserProfile(user1, ctx);
    await createUserProfile(user2, ctx);
    await db.insert(hospitals).values(testHospital);

    const [ts1] = await db
      .insert(timesheets)
      .values({
        userId: user1.id,
        hospitalId: testHospital.id,
        startTime: new Date('2024-01-01T09:00:00.000Z'),
        endTime: new Date('2024-01-01T17:00:00.000Z'),
        status: 'draft',
      })
      .returning();

    const [ts2] = await db
      .insert(timesheets)
      .values({
        userId: user2.id,
        hospitalId: testHospital.id,
        startTime: new Date('2024-01-02T09:00:00.000Z'),
        endTime: new Date('2024-01-02T17:00:00.000Z'),
        status: 'submitted',
      })
      .returning();

    testTimesheetIds.push(ts1.id, ts2.id);
  });

  afterAll(async () => {
    const db = await new PppDb(ctx).getDb();
    for (const id of testTimesheetIds) {
      await db.delete(timesheets).where(eq(timesheets.id, id));
    }
    await db.delete(users).where(eq(users.id, user1.id));
    await db.delete(users).where(eq(users.id, user2.id));
    await db.delete(hospitals).where(eq(hospitals.id, testHospital.id));
  });

  it('should return only user-specific timesheets', async () => {
    const result = await getTimesheetsByUserId(user1.id, ctx);

    expect(result).toBeInstanceOf(Array);
    expect(result.length).toBeGreaterThan(0); // Verify data exists
    result.forEach(t => expect(t.userId).toBe(user1.id)); // Always runs
  });

  it('should return different timesheets for different users', async () => {
    const user1Results = await getTimesheetsByUserId(user1.id, ctx);
    const user2Results = await getTimesheetsByUserId(user2.id, ctx);

    expect(user1Results.length).toBeGreaterThan(0);
    expect(user2Results.length).toBeGreaterThan(0);

    const user1Ids = user1Results.map(t => t.id);
    const user2Ids = user2Results.map(t => t.id);
    const hasOverlap = user1Ids.some(id => user2Ids.includes(id));
    expect(hasOverlap).toBe(false);
  });

  it('should return all timesheets for admin', async () => {
    const all = await getAllTimesheets(ctx);

    expect(all).toBeInstanceOf(Array);
    expect(all.length).toBeGreaterThanOrEqual(2);

    const userIds = all.map(t => t.userId);
    expect(userIds).toContain(user1.id);
    expect(userIds).toContain(user2.id);
  });
});

Internal documentation — org members only