Skip to content

test: fix precommit errors to achieve 100% coverage for api.ts

Suma Pullaiahgari requested to merge tests/coverage-suma into develop

Overview

This MR improves the test coverage for src/lib/api.ts to 100% (statements, functions, lines) and ≥97% branches by adding comprehensive unit tests. This change ensures all API client functions are thoroughly tested, reducing the risk of undetected bugs and improving code maintainability.


What does this MR do and why?

Motivation:

  • Current test coverage for api.ts was incomplete (~70% statements, ~45% branches)
  • Multiple API functions lacked complete test coverage for edge cases and error handling
  • High coverage is required for production confidence and CI/CD pipeline requirements

Approach:

  • Added 40+ new test cases covering all uncovered API functions
  • Tested all edge cases (null, undefined, empty, invalid data)
  • Tested all error handling paths (404, 500, non-Axios errors)
  • Tested interceptors (token injection, 401 handling, cleanup)

Trade-offs:

  • Branch coverage is 97.89% (not 100%) because 2 branches are untestable without source modifications:
    1. Environment variable fallback (import.meta.env.VITE_SERVER_URL ?? '')
    2. Question ID fallback in createOrUpdateKYP (|| id)
  • These branches depend on build-time constants and cannot be controlled from tests

Constraint: Source file src/lib/api.ts was NOT modified — only test file was changed.


Changes Made

Files Modified:

  • tests/lib/api.test.ts — Added 40+ new test cases (+682 lines)

New Test Coverage:

Test Category Functions Tested Test Count
Auth APIs login, getCurrentUser, sendOtp, signup, resetPassword 6
Doctor APIs getAllDoctors, getDoctorById, createDoctor, updateDoctor, registerDoctorForCamp 7
Patient APIs createPatient, getPatient, updatePatient, searchPatients, getPatientByPhone 12
Special Functions getNewBookNo (all response types) 9
Camp Functions getLatestMedicalCamp (all date scenarios) 4
Volunteer APIs getVolunteerCampSignupStatus (localStorage handling) 7
Queue APIs getAllQueue, getDoctorQueue, getPatientQueueStatus 5
Consultation APIs getPatientConsultations, updateConsultation, prescriptions 8
Medicine APIs getMedicines, createMedicine, updateMedicine 5
Medical Camp APIs getAllMedicalCamps, createMedicalCamp, updateMedicalCamp, deleteMedicalCamp 4
User Management getAllUsers, getUserById, updateUser, assignRole, removeRole 6
Role Request APIs createRoleRequest, getMyRoleRequests, getRoleRequests, reviewRoleRequest 7
Analytics APIs getCampAnalytics, getMedicinesAnalytics, getDoctorsAnalytics, getDoctorsAnalyticsWithNames 10
Family APIs createFamily, addFamilyMember, getFamilyById, getFamilyMembersByBookNo 5
Volunteer Camp volunteerSignupForCamp, markVolunteerAttendance 2
Error Handling getPatientCampHistory (404, 500, non-Axios) 2
KYP APIs createOrUpdateKYP, getKYPByPatientAndMonth 3
Interceptors setupAuthInterceptors (token, 401, cleanup) 7
Utilities isApiError type guard 4
User APIs getUsersByPhone 1

Total: 138 tests (increased from 98)


Technical Details

Coverage Achieved:

Metric Before After
Statements ~70% 100%
Branches ~45% 97.89%
Functions ~81% 100%
Lines ~70% 100%

Mocking Strategy:

  • Used vi.mock('axios') to mock axios instance
  • Used beforeEach to clear mocks between tests for isolation
  • Used vi.stubGlobal() for localStorage mocking
  • All mock data properly typed with TypeScript interfaces

TypeScript Fixes Applied:

  • Added attendance property to VolunteerCampSignupStatus mocks
  • Added all required properties to FamilyMemberResponse mocks (relationship, created_at, book_no, user_name, user_age, user_phone_no)

Type of Change

  • 🐛 Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to change)
  • 📝 Documentation update
  • 🎨 UI/UX improvement
  • ️ Refactor (no functional changes)
  • Performance improvement
  • 🧪 Test update
  • 🔧 Configuration change
  • 🚨 Security fix

Related Issues / References

Link to related issues using GitLab syntax:


Screenshots or Screen Recordings

before image after image


How to Set Up and Validate Locally

  1. Checkout this branch:

    git checkout tests/coverage-suma
  2. Install dependencies (if any changed):

    npm install
  3. Run the API tests:

    npm run test:run -- tests/lib/api.test.ts
  4. Verify coverage:

    npm run test:coverage
  5. Check coverage report for src/lib/api.ts:

    • Statements: 100%
    • Functions: 100%
    • Lines: 100%
    • Branches: ≥97%
  6. Verify source file unchanged:

    git diff src/lib/api.ts
    # Should show no changes
  7. Run full build to ensure no TypeScript errors:

    npm run build

Testing Done

  • Manual testing completed
  • Unit tests added/updated

Test Cases Covered:

Scenario Expected Result Status
All API functions called correctly Endpoints called with correct URLs
All responses returned correctly Mock data returned as expected
Edge cases (null, undefined, empty) Handled gracefully without errors
Error handling (404, 500, non-Axios) Errors propagated correctly
Interceptors add auth tokens Token injected in headers
Interceptors handle 401 onUnauthorized callback called
Interceptors cleanup Eject functions called
Source file unchanged Zero modifications to api.ts
All TypeScript types correct No type errors
Build successful No compile errors

Code Quality Checklist

Code Standards

  • Code follows project conventions (naming, structure, formatting)
  • No console.log() or debugger statements left in code
  • No unused imports, variables, or functions
  • No duplicate code and use of existing components for reusability
  • i18n check passed with no hardcoded strings in codebase for i18n support
  • TypeScript types are properly defined (no any unless justified)
  • ESLint and Prettier checks pass

React Best Practices

  • N/A — Test file only, no React components modified

Component Patterns

  • N/A — Test file only, no UI components modified

API & Data Fetching

  • All API functions tested with mocked axios
  • Loading and error states handled in tests
  • API types imported from src/types/api.ts
  • Mock data properly typed

Error Handling

  • Errors are caught and handled gracefully in tests
  • Error propagation tested for all error types
  • Network failures handled appropriately in tests

Documentation

  • README.md updated (if setup steps changed) — N/A
  • .env.example updated (if new env vars added) — N/A
  • CHANGELOG.md updated (if applicable) — N/A

Known Limitations / Technical Debt

Branch Coverage Limitation:

  • 2 branches remain uncovered (97.89% instead of 100%):
    1. Line 70: const API_BASE_URL = import.meta.env.VITE_SERVER_URL ?? '';
      • The ?? '' fallback only executes when env var is undefined
      • Cannot be controlled from test code without vitest config changes
    2. Line 406: ALL_QUESTIONS.find(q => q.id === id)?.question || id;
      • The || id fallback executes when question not found
      • All q1-q20 exist in constants file
      • Cannot test without modifying constants fil

Additional Notes

  • Constraint Met: Only tests/lib/api.test.ts was modified; src/lib/api.ts remains unchanged
  • Pre-commit Hooks: All hooks passed (lint, test, coverage, build, knip)
  • Build: Successful with no TypeScript errors
  • Total Tests: 138 tests passing (increased from 98)

MR Acceptance Checklist

  • Quality & correctness verified
  • Maintainability improved (better test coverage)
  • Review by teammate required
  • Product owner review (if applicable)

Merge request reports

Loading