Skip to content

PPP Mobile App — Testing Strategy ​

Spec-driven BDD: the two-tier model ​

The PPP mobile app is an Expo Router shell whose screens render the PPP web app (instances/ppp) inside react-native-webview (e.g. app/(tabs)/dashboard mounts <WebView path="ppp-dashboard" /> → WEB_URL/ppp-dashboard?app=1). So ~80% of the mobile UI is the web app, while a thin native shell owns auth, push, geofenced timesheets, HealthKit, secure storage and the native↔web bridge.

That architecture dictates a two-tier strategy. Both tiers are spec-driven: acceptance criteria live once in docs/features/mobile.md and are made executable as Gherkin scenarios — there are no duplicate, drift-prone mobile specs.

Tier 1 — Cross-engine web BDD (fast, cheap, broad) ​

The existing @mobile-tagged scenarios in instances/ppp/e2e/bdd/features/ run on true mobile engines, not a resized desktop browser:

Playwright projectEngine / deviceMirrors
bdd-mobile-webkitWebKit / iPhone 14iOS WKWebView (is WebKit)
bdd-mobile-chromiumChromium / Pixel 7Android System WebView (Blink)

These descriptors bring real mobile user-agent, touch input, isMobile, and a handheld viewport. App-mode is exercised via the existing steps that append ?app=1 and inject the window.ReactNativeWebView bridge stub (e2e/bdd/steps/mobile-nav.steps.ts).

Run locally pnpm --filter @ppp-org/instance-ppp test:bdd:mobile (or :mobile:uat). In CI: .github/workflows/mobile-web-bdd.yml runs both engines against live UAT daily, on GitHub-hosted ubuntu runners.

Caveat — not a full replacement for devices. Playwright's WebKit ≈ but ≠ iOS WKWebView, and Chromium-mobile ≈ but ≠ real Android System WebView. Viewport emulation also misses safe-area insets, native keyboard, and scroll momentum. Tier 1 is the broad first line; Tier 2 covers what only a real OS can.

Tier 2 — Native-shell E2E on real engines (Maestro) ​

Maestro flows drive the native shell and OS integrations no browser can reach:

SuiteSurface
mobile/ppp/.maestro/ + e2e/*.yamlLogin + core WebView journeys on the real build
mobile/ppp/e2e/native/Deep links, geofence auto-timesheet, location/health permissions, secure-store session, push (manual)
  • Android: GitHub-hosted ubuntu emulator (mobile-e2e.yml, android-e2e).
  • iOS: the mac-mini self-hosted runner (mobile-e2e.yml, ios-e2e, runs-on: [self-hosted, macOS, ARM64, mac-mini]). Apple licensing requires macOS to run the iOS Simulator — that is the Mac mini's job. The runner is registered; it must be online (the GitHub Actions runner agent running on the box) for iOS E2E to dispatch.

See mobile/ppp/e2e/native/README.md for the native flow catalogue.


Unit / component / integration layers ​

Jest (jest-expo) is the correct framework here. Vitest (used in the monorepo web/backend packages) cannot process Metro transforms or mock native modules.


Why Testing Is Critical Here ​

This app handles clinical medical data for UK and Australian medical professionals:

  • Surgical logbook entries (patient procedures, outcomes)
  • CPD compliance records submitted to regulatory bodies
  • Wellness data used in appraisals
  • Automatic timesheet creation based on physical location

A bug in the geofencing or timesheet creation logic could:

  • Create incorrect timesheets that affect clinician pay
  • Lose CPD records that a clinician needs for annual appraisal
  • Expose health data due to a logic error in region routing

Proposed Test Suite ​

Layer 1: Unit Tests (no native modules) ​

Target: Pure logic functions that can run without native APIs.

Session Store Tests (lib/stores/__tests__/sessionStore.test.ts) ​

typescript
import { renderHook, act } from '@testing-library/react-native';
import { useSessionStore, type SessionUser } from '../sessionStore';

describe('sessionStore', () => {
  beforeEach(() => useSessionStore.getState().clear());

  it('sets and retrieves access token', () => {
    act(() => useSessionStore.getState().setAccessToken('test-token'));
    expect(useSessionStore.getState().accessToken).toBe('test-token');
  });

  it('clears token on removeAccessToken', () => {
    act(() => {
      useSessionStore.getState().setAccessToken('test-token');
      useSessionStore.getState().removeAccessToken();
    });
    expect(useSessionStore.getState().accessToken).toBeNull();
  });

  it('clears user and token on clear()', () => {
    const mockUser = { id: 1 } as SessionUser;
    act(() => useSessionStore.getState().setUser(mockUser));
    act(() => useSessionStore.getState().clear());
    expect(useSessionStore.getState().user).toBeNull();
    expect(useSessionStore.getState().accessToken).toBeNull();
  });
});

Notification History Logic (lib/services/__tests__/location-service.test.ts) ​

typescript
// Test: wasNotifiedToday returns false for new hospital
// Test: wasNotifiedToday returns true after markAsNotified called today
// Test: wasNotifiedToday returns false for yesterday's entry after cleanupOldHistory
// Test: notificationLock prevents duplicate processing for same hospitalId
// Test: geofence ENTER with existing timesheet skips creation
// Test: geofence EXIT with no active timesheet returns Success without mutation

tRPC Client Config (lib/utils/__tests__/trpcClient.test.ts) ​

typescript
// Test: authorization header contains Bearer <token>
// Test: TRPC_URL matches Constants.expoConfig.extra.TRPC_URL

Layer 2: Component Tests (with RNTL) ​

Requires installing @testing-library/react-native.

Setup needed (jest.setup.ts):

typescript
import '@testing-library/jest-native/extend-expect';
jest.mock('react-native-mmkv', () => ({
  MMKV: jest.fn(() => ({
    getString: jest.fn(),
    set: jest.fn(),
    delete: jest.fn(),
  })),
}));
jest.mock('expo-constants', () => ({
  default: {
    expoConfig: {
      extra: { TRPC_URL: 'https://test.trpc.url', WEB_URL: 'https://test.web.url' },
    },
  },
}));

Smoke tests for all 19 tab screens:

typescript
describe('Dashboard screen', () => {
  it('renders without throwing', () => {
    const { getByText } = render(<Dashboard />);
    // verify key elements present
  });
  it('is accessible', () => {
    const { getByRole } = render(<Dashboard />);
    // Use @testing-library/jest-native matchers — axe-core is DOM-only
    // and not compatible with React Native's component tree
    expect(getByRole('header')).toBeVisible();
  });
});

Layer 3: Integration Tests ​

Auth Flow Integration (app/__tests__/index.test.tsx) ​

typescript
// Mock react-native-webview
jest.mock('react-native-webview', () => ({ WebView: 'WebView' }));

// Test: handleMessage with type='tokenFound' calls setAccessToken
// Test: handleMessage with type='localStorage' containing idToken key calls setAccessToken
// Test: handleMessage with logout=1 calls removeAccessToken
// Test: handleMessage with malformed JSON does not throw
// Test: jsCode is switched for logout route

Geofencing Integration ​

typescript
// Mock expo-location, expo-task-manager, trpcClient
// Test: setupHospitalGeofences calls Location.startGeofencingAsync with correct regions
// Test: startLocationTracking waits for task definition before starting
// Test: stopLocationTracking stops both location updates and geofencing

Layer 4: E2E Tests ​

Decided. E2E is delivered by the two-tier model above — Tier 1 cross-engine web BDD (Playwright) + Tier 2 native-shell flows (Maestro). Detox was not adopted. The flows below are the original critical-path list, now implemented under mobile/ppp/e2e/ and mobile/ppp/e2e/native/.

Critical flows to automate:

  1. Login flow

    • App launches → WebView appears → Cognito login form
    • User enters credentials → Dashboard loads → tab navigation available
  2. Logbook entry flow

    • Navigate to Logbook tab
    • Tap "Add procedure"
    • Fill in required fields
    • Submit → entry appears in list
  3. Timesheet manual entry

    • Navigate to Timesheet tab
    • Create new timesheet with hospital, start/end time
    • Submit → timesheet saved
  4. Wellness questionnaire

    • Navigate to Wellness tab
    • Complete questionnaire
    • Submit → score displayed

Maestro test example (e2e/login.yaml):

yaml
appId: com.professionalperformanceportfolio.ppp.development
---
- launchApp
- assertVisible: 'Sign In'
- tapOn: 'Email'
- inputText: 'test@example.com'
- tapOn: 'Password'
- inputText: 'TestPassword123!'
- tapOn: 'Sign in'
- assertVisible: 'PPP Dashboard'

Compliance-Required Tests ​

The following tests are required for GDPR/AU Privacy Act compliance:

TestRegulationDescription
UK users routed to UK endpointGDPR Art. 46TRPC_URL should resolve to EU region when user.countryCode === 'GB'
AU users routed to AU endpointPrivacy Act APP 8TRPC_URL should resolve to AP region when user.countryCode === 'AU'
Token cleared on logoutGDPR Art. 17MMKV session-storage key is null after clear()
MMKV encryption key presentGDPR Art. 32new MMKV({ encryptionKey: ... }) — key must be non-empty
Consent captured before HealthKit accessGDPR/AU Health Records ActinitHealthKit not called before user has seen consent screen

Coverage Targets ​

LayerTarget CoverageRationale
Unit (stores, utils, services)≥ 90%Pure logic, no native deps
Component (screens)≥ 80%Smoke + accessibility only
Integration (auth, geofencing)≥ 70%Critical paths covered
E2ETop 5 user flowsRegulatory requirement

Required Package Additions ​

bash
pnpm add -D @testing-library/react-native @testing-library/jest-native
# Note: do NOT install jest-environment-jsdom — React Native tests use the
# 'react-native' test environment provided by jest-expo, not jsdom.
# Note: do NOT install axe-core — it is DOM-only and incompatible with React
# Native. Use @testing-library/jest-native matchers (toBeVisible, toBeEnabled,
# getByRole) for accessibility assertions instead.

package.json update:

json
"jest": {
  "preset": "jest-expo",
  "setupFilesAfterEnv": ["<rootDir>/jest.setup.ts"],
  "coverageThreshold": {
    "global": { "lines": 80, "branches": 70, "functions": 80, "statements": 80 }
  },
  "collectCoverageFrom": [
    "app/**/*.{ts,tsx}",
    "lib/**/*.{ts,tsx}",
    "!**/__tests__/**",
    "!**/node_modules/**"
  ]
}

Internal documentation — org members only