Test Coverage Enhancement Task
Please analyze and improve the test coverage for this codebase following the established testing strategy. Run npm test -- --coverage to get current coverage and target ≥80% coverage.
Use parallel subagents to run tests and improve coverage.
1. Coverage Analysis & Strategy
- Run
npm test -- --coverageto identify gaps in coverage - Focus on files in
src/lib/utils/,src/lib/services/,app/api/, andsrc/components/ - NEVER test repositories in
src/lib/repositories/- these should remain untested - Prioritize critical business logic and complex functions
2. Project-Specific Testing Rules
Mocking Strategy (CRUCIAL)
- NEVER import or use
@prisma/clientdirectly in test files - NEVER mock
@prisma/client- if errors occur, mock the specific repository instead - ALWAYS mock repository modules used by code under test:
// At top of test file:
jest.mock("@/lib/repositories/userRepository", () => ({
getById: jest.fn(),
updateName: jest.fn(),
}));
const mockUserRepository = require("@/lib/repositories/userRepository");
// In test:
mockUserRepository.getById.mockResolvedValue({ id: '1', name: 'Ana García' });
File Structure & Placement
- Place tests in
__tests__/unit/for utility functions and services - Place tests in
__tests__/integration/for components and API handlers - Tests can also be co-located with source files (
*.test.tsx)
3. Testing Patterns by File Type
Utility Functions (`src/lib/utils/`, `src/lib/services/`)
// Mock external libraries at module level
jest.mock("langfuse", () => ({
Langfuse: jest.fn(),
TextPromptClient: jest.fn(),
}));
// Mock console methods and restore in cleanup
const consoleLogSpy = jest.spyOn(console, "log").mockImplementation(() => {});
afterAll(() => consoleLogSpy.mockRestore());
API Route Handlers (`app/api/`)
- Mock repository dependencies (never Prisma directly)
- Test request/response flow with different HTTP methods
- Verify error handling and proper status codes
- Mock authentication/authorization where needed
React Components (`src/components/`, `app/`)
- Use
@testing-library/reactfor user interactions - Test via user actions and observable output
- Mock API calls and external services
- Test accessibility and responsive behavior
4. Test Data & Edge Cases
Spanish Business Context
Use realistic Spanish business data matching the codebase:
const testData = {
customers: [
{ name: "Ana García", phone: "+34611223344" },
{ name: "José María Fernández-Vázquez", phone: "+34612345678" },
],
businesses: [
{ name: "Salon Bella", address: "Calle Mayor 1, Madrid" },
{ name: "Peluquería Ñoña & Coiffeur", services: ["corte", "peinado"] },
],
specialChars: "¡Hola! ¿Cómo está usted?",
emojis: "💇♀️✂️🎨",
};
Mandatory Edge Cases for All Functions
Test these scenarios comprehensively:
nullandundefinedvalues- Empty objects
{}and arrays[] - Complex nested objects with multiple levels
- Objects with special characters and emojis
- Circular references (for inspection utilities)
- Functions within objects
- Large data sets (performance considerations)
5. Environment & TypeScript Considerations
Environment Variables
- AVOID direct assignment to
process.env.NODE_ENV(TypeScript read-only) - USE
expect.any(Boolean)for environment-dependent behavior
// ✅ DO: Test actual behavior
expect(mockUtil.inspect).toHaveBeenCalledWith(testObj, {
depth: null,
colors: process.env.NODE_ENV === "development",
});
// ❌ DON'T: Mock NODE_ENV directly
// process.env.NODE_ENV = "development"; // TypeScript error
6. Test Quality Standards
Arrange-Act-Assert Structure
- Arrange: Set up test data and mocks
- Act: Execute the function/behavior being tested
- Assert: Verify expected outcomes and side effects
Descriptive Naming
- Use clear
describeblocks that explain the component/function context - Write
it/testdescriptions that read like specifications - Group related tests logically
Mock Cleanup
- Always restore spies and mocks in
afterAllorafterEach - Isolate tests to avoid shared state
- Clear mocks between tests when needed
7. Implementation Checklist
For each file with coverage gaps:
- [ ] Check if it's a repository (skip if yes)
- [ ] Identify uncovered lines, branches, and functions
- [ ] Mock all external dependencies appropriately
- [ ] Write tests covering happy path and edge cases
- [ ] Use Spanish business context in test data
- [ ] Follow AAA pattern with clear descriptions
- [ ] Test error handling and boundary conditions
- [ ] Verify mock calls with expected parameters
- [ ] Clean up mocks and spies properly
8. Coverage Verification
After implementing tests:
- Run
npm test -- --coverageto verify improvement - Ensure coverage meets ≥80% threshold
- Focus on statement, branch, and function coverage
- Address any remaining critical gaps
Start by analyzing current coverage, then systematically address gaps while strictly following the mocking strategy and using realistic Spanish business data.