Skip to content

Extension SDK

Testing extensions

The local test harness, service mocks, fixture snapshots, and CI integration. How to ship extensions with confidence.

Key points

  • The SDK ships with a test harness that simulates the sandboxed runtime locally
  • Services are mocked through the same injection pattern the runtime uses
  • Tests run with your normal test runner — the harness has no opinion on Vitest vs. Jest
  • CI should run tests, validate the manifest, and dry-run against sandbox before merging

The test harness

Extensions don’t run as standalone scripts — they need the runtime context, injected services, and the typed input marshaling. The SDK’s test harness provides all of that locally so you can write normal unit tests:

tests/TravelTimeCalculator.test.tstypescript
import { describe, expect, it } from 'vitest';
import { createTestHarness } from '@flexischeduler/extension-sdk/testing';
import { TravelTimeCalculator } from '../src/calculators/TravelTimeCalculator';

describe('TravelTimeCalculator', () => {
  const harness = createTestHarness({
    extension: new TravelTimeCalculator(),
    services: {
      googleMaps: mockGoogleMaps(),
    },
  });

  it('adds wheelchair buffer to the base route time', async () => {
    const result = await harness.calculate({
      origin: { lat: 40.7128, lng: -74.0060 },
      destination: { lat: 40.7589, lng: -73.9851 },
      mobility_type: 'wheelchair',
      time_of_day: new Date('2026-05-08T10:00:00Z'),
    });

    // Base 10 min + wheelchair buffer 15 min = 25 min, rounded to 25
    expect(result).toBe(25);
  });

  it('throws on invalid mobility type', async () => {
    await expect(
      harness.calculate({
        origin: { lat: 0, lng: 0 },
        destination: { lat: 0, lng: 0 },
        mobility_type: 'bogus' as any,
      }),
    ).rejects.toThrow();
  });
});

createTestHarness wraps your extension in a context that mirrors the production runtime — same injection model, same input validation, same timeout enforcement. If your test passes, the extension behaves the same way in production.

Mocking services

Every external service your extension uses needs a mock for tests. The SDK provides mockService for typed mocks that match the production client interface:

tests/mocks/googleMaps.tstypescript
import { mockService } from '@flexischeduler/extension-sdk/testing';

const mockGoogleMaps = () =>
  mockService<GoogleMapsClient>({
    directions: async ({ origin, destination }) => ({
      durationMinutes: distance(origin, destination) * 1.5,
      distanceMeters: distance(origin, destination) * 1000,
      polyline: 'mock_polyline',
    }),
  });

The mock implements the same interface as the production client, so TypeScript catches signature drift if the real client’s API changes. For complex services, the SDK ships pre-built mocks (mockNetSmart, mockGoogleMaps) with sensible defaults you can override.

Don’t make real network calls in tests

Tempting to skip the mock and call the real API. Don’t. It makes tests slow, flaky, and dependent on external service uptime. Use mocks for unit tests; use flexischeduler-cli deploy --target sandbox for integration testing against real services.

Testing each extension type

Calculators

Test inputs and outputs directly. Calculators are pure functions — same input, same output, no side effects. The earlier TravelTimeCalculator example covers this. Focus on:

  • Edge cases (zero distance, same origin/destination, extreme times)
  • Each branch of buffer/multiplier logic
  • External service failure handling
  • Cache hit and miss paths if you use the runtime cache

Validators

Test each outcome — pass, warn, fail — and assert the structured result shape. Failure codes and suggestions are part of your contract; verify them explicitly:

tests/CarePlanValidator.test.tstypescript
import { describe, expect, it } from 'vitest';
import { createTestHarness } from '@flexischeduler/extension-sdk/testing';
import { CarePlanValidator } from '../src/validators/CarePlanValidator';

describe('CarePlanValidator', () => {
  const harness = createTestHarness({
    extension: new CarePlanValidator(),
    services: {
      netSmart: mockNetSmart({
        carePlans: {
          'CP-114782': {
            approved_activities: ['clinic_visit', 'home_care_visit'],
            review_due_within_days: 30,
          },
        },
      }),
    },
  });

  it('passes when activity is in the approved list', async () => {
    const result = await harness.validate({
      event: { activity_type: 'home_care_visit' /* ... */ },
      participant: { attributes: { care_plan_id: 'CP-114782' } /* ... */ },
    });

    expect(result.status).toBe('pass');
  });

  it('fails when activity is not approved', async () => {
    const result = await harness.validate({
      event: { activity_type: 'transport_only' /* ... */ },
      participant: { attributes: { care_plan_id: 'CP-114782' } /* ... */ },
    });

    expect(result.status).toBe('fail');
    expect(result.error?.code).toBe('CARE_PLAN_MISMATCH');
    expect(result.error?.suggestions).toContain('clinic_visit');
  });
});

Allocators

Test that ranking is stable, deterministic, and matches your scoring intent. Pass in candidate lists with predictable properties and assert the resulting order:

it('boosts merge opportunities above non-merge candidates', async () => {
  const result = await harness.rank(
    { primary_entity_id: 'ent_pt_9001', /* ... */ },
    [
      { id: 'slot_a', baseScore: 50, /* same-day as existing */ },
      { id: 'slot_b', baseScore: 60, /* different day */ },
    ],
  );

  // slot_a starts lower but gets the merge boost
  expect(result[0].id).toBe('slot_a');
  expect(result[0].metadata?.merge_opportunity).toBe(true);
});

Fixtures and snapshots

For complex extensions, raw input objects in test files become unwieldy fast. Move them to fixtures:

// tests/fixtures/participants.ts
export const wheelchairParticipant = {
  id: 'ent_pt_9001',
  attributes: {
    care_plan_id: 'CP-114782',
    mobility_requirements: 'wheelchair',
    daily_hour_limit: 8,
  },
};

// tests/CarePlanValidator.test.ts
import { wheelchairParticipant } from './fixtures/participants';

it('handles a wheelchair participant', async () => {
  const result = await harness.validate({
    event: someEvent,
    participant: wheelchairParticipant,
  });
  expect(result.status).toBe('pass');
});

For allocator output, snapshot testing the ranked list catches ranking changes that may be unintentional:

expect(result).toMatchSnapshot();

Snapshots are most valuable when ranking weights change — the diff makes the impact visible in code review.

CI integration

The recommended CI pipeline runs four checks: install dependencies, validate the manifest, run unit tests, build (typecheck and bundle). For PRs, optionally dry-run a deploy against the sandbox environment:

.github/workflows/extensions.ymlyaml
# .github/workflows/extensions.yml
name: Extensions CI

on: [pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: '20' }

      - name: Install dependencies
        run: npm ci

      - name: Validate manifest
        run: npx flexischeduler-cli validate

      - name: Run extension tests
        run: npm test

      - name: Build (typecheck + bundle)
        run: npx flexischeduler-cli build

      # Optional: dry-run against the sandbox environment
      - name: Sandbox dry-run
        if: github.event_name == 'pull_request'
        run: npx flexischeduler-cli deploy --target sandbox --dry-run
        env:
          FLEXI_SIGNING_KEY: ${{ secrets.FLEXI_SIGNING_KEY }}

The --dry-run flag verifies signing, manifest validity, and runtime compatibility without actually deploying — useful for catching issues that only manifest in the production runtime, like attempting to import a blocked module.

Best practices

  • Test the contract, not the implementation. Assert on result shapes (status, code, suggestions), not on internal helper functions. Implementation can change; contract should not.
  • Cover external service failures. What happens when Google Maps returns 503? When a CRM call times out? Your tests should answer.
  • Test cache behavior. If you use ctx.cache, write tests for both cache hit and cache miss. The harness exposes a resetCache() helper for this.
  • Don’t test the runtime. Don’t write tests verifying that timeouts trigger or sandboxing blocks bad imports — those are the runtime’s responsibility, not yours. Test your code’s behavior when a timeout occurs, not that the timeout itself works.
  • Run the manifest validator in CI. flexischeduler-cli validate catches manifest typos, unknown extension types, and version conflicts before they hit production.

Coverage targets

Aim for ~80% line coverage on extensions. Higher than typical application code because extensions run in critical paths and bugs are expensive — slow validators slow scheduling for every booking that depends on them.