1 Dev Playwright Mock Fixtures
Forgejo Actions edited this page 2026-09-25 16:38:07 +00:00

Playwright API Mock Fixtures — Patterns & Template

Every Memories Playwright test uses page.route() to mock backend API responses. This doc documents the standard patterns so new tests are consistent and no mocks are missed during frontend refactors.

Shared Boilerplate Mocks

These mocks are needed by almost every page in the app. Add them at the top of each test or group them in a routeShellApis() helper:

Session mock (/api/session)

await page.route('**/api/session', async (route) => {
  await route.fulfill({
    json: {
      userAccountId: '11111111-1111-4111-8111-111111111111',
      systemRole: 'super_admin',     // or 'user' if non-admin test
      ownerId: '22222222-2222-4222-8222-222222222222',
      displayName: 'Christian'
    }
  });
});
  • Role super_admin for pages with admin features, user otherwise.
  • Owner ID and user ID must be distinct to test ownership correctly.

App version mock (/api/app/version)

await page.route('**/api/app/version', async (route) => {
  await route.fulfill({ json: { apiVersion: '1.35.0' } });
});

Not every test needs this — only pages that display version info. Check the page source or existing tests.

Processing summary mock (/api/processing-summary**)

await page.route('**/api/processing-summary**', async (route) => {
  await route.fulfill({
    json: {
      incompleteMediaCount: 0,
      hasActiveWork: false,
      failedCount: 0,
      activities: []
    }
  });
});

Auto-approval retrospective-status mock

await page.route('**/api/person-assignments/auto-approval-policy/retrospective-status', async (route) => {
  await route.fulfill({ json: null });
});

Group all shared mocks into a single helper per spec file:

async function routeShellApis(page: Page) {
  await page.route('**/api/session', async (route) => {
    await route.fulfill({ json: { userAccountId: '...', systemRole: 'user', ownerId: '...', displayName: 'Christian' } });
  });
  await page.route('**/api/processing-summary**', async (route) => {
    await route.fulfill({ json: { incompleteMediaCount: 0, hasActiveWork: false, failedCount: 0, activities: [] } });
  });
  await page.route('**/api/person-assignments/auto-approval-policy/retrospective-status', async (route) => {
    await route.fulfill({ json: null });
  });
  await page.route('**/api/app/version', async (route) => {
    await route.fulfill({ json: { apiVersion: '1.35.0' } });
  });
}

Call from each test: await routeShellApis(page);

UUID / ID Convention

All UUIDs in tests use a consistent pattern so they are visually distinct:

Purpose UUID pattern
Current user (userAccountId) 11111111-1111-4111-8111-111111111111
Owner / ownerId 22222222-2222-4222-8222-222222222222
Primary entity (person, album, media) aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa
Secondary entity bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb
Tertiary entity cccccccc-cccc-4ccc-8ccc-cccccccccccc
Continue alphabetically for more entities dddd…, eeee…, ffff…

Endpoint-Specific Mock Patterns

List endpoints with pagination

await page.route(/\/api\/person-assignments\/resolved-people(?:\?.*)?$/, async (route) => {
  const cursor = new URL(route.request().url()).searchParams.get('cursor') ?? 'first';
  await route.fulfill({ json: { people: peopleByPage[cursor] ?? [], nextCursor: null } });
});

Detail endpoints

await page.route(`**/api/person-assignments/people/${personId}`, async (route) => {
  await route.fulfill({ json: { personRecordId: personId, displayName: 'William', ... } });
});

Mutation endpoints (POST/PUT) — track with local state

let savedBody: unknown;

await page.route(`**/api/discovery/class-instances/${instanceId}`, async (route) => {
  savedBody = route.request().postDataJSON();
  await route.fulfill({ json: { ...instanceView('active'), displayName: 'Fido Wiwie' } });
});

// Later in test:
expect(savedBody).toEqual({ displayName: 'Fido Wiwie', aliases: ['dog', 'good boy'] });

Conditional response based on query param

await page.route(/\/api\/discovery\/class-instances(?:\?.*)?$/, async (route) => {
  const url = new URL(route.request().url());
  const lifecycleState = url.searchParams.get('lifecycleState') ?? 'active';
  if (lifecycleState === 'archived') {
    await route.fulfill({ json: [instanceView('archived')] });
    return;
  }
  await route.fulfill({ json: [instanceView('active')] });
});

Long-running / hanging requests

await page.route(`**/api/albums/${albumId}`, () => {
  // Intentionally never fulfills — tests timeout handling
});

Image / binary responses

await page.route(`**${previewUrl}`, async (route) => {
  await route.fulfill({
    contentType: 'image/svg+xml',
    body: '<svg xmlns="http://www.w3.org/2000/svg" width="256" height="256"><rect width="256" height="256" fill="#065f46"/></svg>'
  });
});

Factory Helpers for Test Data

Use inline factory functions to produce consistent mock data:

function instanceView(lifecycleState: 'active' | 'archived') {
  return {
    classInstanceId: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',
    domainKey: 'people',
    classKey: 'person',
    displayName: 'Fido',
    aliases: ['dog'],
    lifecycleState,
    visibility: 'owner_private',
    createdAt: '2026-05-29T09:00:00Z',
    updatedAt: '2026-05-29T10:00:00Z'
  };
}

API-Mock Completeness Cross-Check

When adding a new API call in a frontend file (page, component, store):

  1. Check the existing test file for that page/component.
  2. Verify every new endpoint is mocked before page.goto(), not after.
  3. If the endpoint doesn't exist in the test, add it.
  4. Include the endpoint in your PR handoff summary under "Open questions" if the mock requires real API shape validation.

Every endpoint the frontend calls must have a corresponding mock in the test. If you can add an integration or contract test instead, prefer that — but at minimum, the Playwright mock must exist.