Skip to main content

Overview

Salud uses a multi-layered testing approach to ensure reliability and security across the frontend, backend, and smart contracts.

Testing Philosophy

Quality Standards

  • Smart Contracts: Comprehensive test coverage (security-critical)
  • Backend: API endpoint validation and error handling
  • Frontend: Build verification and linting
  • Integration: Manual end-to-end testing

Test Pyramid

        /\        E2E Tests (Manual)
       /  \       - User flows
      /    \      - Cross-browser
     /      \     
    /--------\    Integration Tests (Manual/Automated)
   /          \   - API endpoints
  /            \  - Contract interactions
 /              \ 
/----------------\ Unit Tests (Automated)
                   - Contract transitions
                   - Utility functions
                   - Component rendering

Smart Contract Testing

The Leo smart contract has the most comprehensive test suite with 17 automated tests.

Running Contract Tests

cd salud_health_records
leo test

# Expected output:
# Test test_create_record ... ok
# Test test_record_types ... ok
# ... (17 tests)
# All tests passed ✓

Test Coverage

The contract test suite (tests/test_salud_health_records.leo) covers:

Record Creation Tests

Verifies basic record creation with valid inputs.Tests:
  • Record is created successfully
  • Owner is set to caller
  • Data fields are stored correctly
  • Record type is valid
Validates all 10 record type categories.Record Types Tested:
  1. General Health
  2. Laboratory Results
  3. Prescriptions
  4. Imaging/Radiology
  5. Vaccination Records
  6. Surgical Records
  7. Mental Health
  8. Dental Records
  9. Vision/Ophthalmology
  10. Other/Miscellaneous
Ensures invalid record types (0, 11+) are rejected.Expects: Assertion failure for out-of-range types

Record ID Tests

Verifies that different inputs produce unique record IDs.Tests:
  • Different data → different IDs
  • Different nonces → different IDs
  • Different patients → different IDs
Confirms same inputs always produce same ID.Tests:
  • Same patient + data + nonce = same ID
  • Useful for client-side ID computation

Access Grant Tests

Tests basic access grant creation.Verifies:
  • Access token is generated
  • Grant is stored in mapping
  • Patient retains record ownership
Validates access token uniqueness.Tests:
  • Different doctors → different tokens
  • Different nonces → different tokens
  • Same inputs → same token (deterministic)
Checks duration clamping to valid ranges.Tests:
  • Minimum: 240 blocks (~1 hour)
  • Maximum: 40,320 blocks (~7 days)
  • Out-of-range values are clamped

Access Verification Tests

Tests successful verification with valid token.Flow:
  1. Create record
  2. Grant access to doctor
  3. Verify access succeeds
Ensures fake tokens are rejected.Tests:
  • Random token → verification fails
  • Wrong token for record → fails
Prevents access by unauthorized doctors.Scenario:
  • Grant to Doctor A
  • Doctor B tries to access
  • Verification fails
Ensures tokens are record-specific.Scenario:
  • Token for Record A
  • Used on Record B
  • Verification fails

Revocation Tests

Tests immediate access revocation.Flow:
  1. Grant access
  2. Revoke access
  3. Verification fails
  4. Access info shows is_revoked: true
End-to-end integration test.Complete Flow:
  1. Patient creates record
  2. Patient grants access to doctor
  3. Doctor verifies access (succeeds)
  4. Patient revokes access
  5. Doctor verification fails

Helper Function Tests

Validates client-side ID computation helper.Purpose: Allows frontend to predict record IDs
Tests public access info retrieval.Returns:
  • Patient address
  • Doctor address
  • Record ID
  • Expiration time
  • Revocation status

Writing New Contract Tests

Example test structure:
// tests/test_salud_health_records.leo

@test
function test_your_feature() {
    // Setup: Create test data
    let patient: address = aleo1...;
    let doctor: address = aleo1...;
    
    // Execute: Call transition
    let record: MedicalRecord = create_record(
        1field, 2field, 3field, 4field,
        1u8,      // record_type
        100field, // data_hash
        42field,  // nonce
        false     // make_discoverable
    );
    
    // Assert: Verify results
    assert_eq(record.owner, patient);
    assert_eq(record.record_type, 1u8);
    assert(record.record_id != 0field);
}
Best Practices:
  • Test one thing per test function
  • Use descriptive function names
  • Add comments explaining what’s being tested
  • Test both success and failure cases
  • Verify security constraints

Backend Testing

The backend uses manual testing and verification.

Running Backend Tests

1

Start the Server

cd backend
npm start
Verify: Server starts without errors on port 3001
2

Test Health Endpoint

curl http://localhost:3001/api/health
Expected Response:
{
  "status": "ok",
  "message": "Salud Health Records API is running"
}
3

Test Wallet Generation

curl -X POST http://localhost:3001/api/wallet/generate
Expected Response:
{
  "success": true,
  "privateKey": "APrivateKey1...",
  "address": "aleo1...",
  "sessionId": "uuid-here"
}
4

Test Wallet Connection

curl -X POST http://localhost:3001/api/wallet/connect \
  -H "Content-Type: application/json" \
  -d '{
    "privateKey": "APrivateKey1zkp..."
  }'
Expected Response:
{
  "success": true,
  "address": "aleo1...",
  "sessionId": "uuid-here"
}
5

Test Record Creation

curl -X POST http://localhost:3001/api/records/create \
  -H "Content-Type: application/json" \
  -d '{
    "sessionId": "your-session-id",
    "encryptedData": "encrypted-medical-data",
    "recordType": 1
  }'

Backend Test Checklist

Manual API Testing with Postman

Collection Setup:
  1. Base URL: http://localhost:3001
  2. Headers: Content-Type: application/json
Test Scenarios:
GET /api/health

Expected: 200 OK
Body: { "status": "ok" }

Frontend Testing

The frontend focuses on build verification and code quality.

Running Frontend Tests

cd frontend
npm run lint

# Checks for:
# - TypeScript errors
# - ESLint rule violations
# - React best practices
# - Unused imports/variables

Frontend Test Checklist

Manual UI Testing

Test on Multiple Browsers:
  • Wallet connection
  • QR code camera access
  • LocalStorage persistence
  • Console errors

Integration Testing

End-to-End User Flows

1

Patient Creates Record

Test Flow:
  1. Open app at http://localhost:5173
  2. Connect wallet (or generate new)
  3. Click “New Record” button
  4. Enter medical data
  5. Submit record
  6. Verify success message
  7. See record in list
Expected Result: Record appears in dashboard
2

Patient Shares Record

Test Flow:
  1. Click “Share” on a record
  2. Enter doctor address (or use default duration)
  3. QR code displays
  4. Verify expiration countdown shows
  5. Screenshot QR code for doctor test
Expected Result: Valid QR code generated
3

Doctor Scans and Views

Test Flow:
  1. Navigate to /doctor route
  2. Connect doctor wallet
  3. Click “Scan QR Code”
  4. Grant camera permission
  5. Scan patient’s QR code
  6. View decrypted record
  7. Verify expiration timer
Expected Result: Record displays with countdown
4

Access Expiration

Test Flow:
  1. Create record with 1-hour duration
  2. Share with doctor
  3. Wait for expiration (or modify block height in demo)
  4. Doctor attempts to view
  5. Verify “Access expired” error
Expected Result: Access denied after expiration

Cross-Platform Testing

Device Matrix:
DeviceOSBrowserPriority
iPhone 12+iOS 15+SafariHigh
iPhone 12+iOS 15+ChromeMedium
Android11+ChromeHigh
DesktopmacOSChrome/SafariHigh
DesktopWindowsChrome/EdgeHigh
DesktopLinuxFirefoxMedium

Testing Best Practices

Before Committing

1

Run All Checks

# Frontend
cd frontend
npm run lint
npm run build

# Backend
cd ../backend
npm start  # Verify starts
# Ctrl+C to stop

# Contract (if changed)
cd ../salud_health_records
leo test
2

Manual Testing

  • Test the feature you changed
  • Test related features
  • Check for console errors
  • Verify mobile responsive (if UI change)
3

Document Changes

  • Update documentation if needed
  • Add comments for complex logic
  • Update API docs if endpoints changed

Before Pull Request

Continuous Testing

During Development

Frontend (with HMR):
cd frontend
npm run dev

# Changes auto-reload
# Check browser console after each change
# Verify functionality manually
Backend (with nodemon):
cd backend
npm run dev

# Server auto-restarts on changes
# Check terminal for errors
# Re-test endpoints after changes
Contract (iterative):
cd salud_health_records

# Make changes to src/main.leo
leo build
leo test

# Fix errors, repeat

Test Data

Demo Mode Test Data

Sample Private Keys (Testnet Only):
APrivateKey1zkp... (generate new for testing)
Sample Medical Records:
{
  "title": "Annual Physical Exam",
  "data": "Blood pressure: 120/80, Heart rate: 72 bpm, Temperature: 98.6°F",
  "recordType": 1
}

{
  "title": "Lab Results - Cholesterol",
  "data": "Total: 180 mg/dL, HDL: 55 mg/dL, LDL: 100 mg/dL",
  "recordType": 2
}
Sample Doctor Address (for testing):
aleo1... (use generated address from "Generate New")

Debugging Tests

Contract Test Failures

# Run with verbose output
leo test --verbose

# Read assertion error messages carefully
# Check expected vs actual values
# Verify test setup matches contract logic

Backend Issues

// Add console logs in server.js
console.log('Request body:', req.body);
console.log('Session data:', sessions.get(sessionId));

// Check for:
// - Missing parameters
// - Type mismatches
// - Aleo SDK errors

Frontend Issues

// Browser DevTools Console
// Check for:
// - API call failures (Network tab)
// - State updates (React DevTools)
// - LocalStorage data (Application tab)
// - Console errors/warnings

Next Steps

Contributing Guide

Learn how to submit tested contributions

Local Setup

Set up your testing environment

Architecture

Understand what you’re testing

API Reference

Test API endpoints comprehensively

Build docs developers (and LLMs) love