Products Search & Suggestions API Tests
Overview
Comprehensive test coverage for the products search and suggestions API endpoints, including search functionality, query validation, caching, rate limiting, and error handling.
Created: November 28, 2025 Status: COMPLETED Coverage: 96.77% (Combined)
API Endpoints Tested
1. /api/products/search - Main Search Route
File: src/app/api/products/search/route.ts
Test File: src/app/api/products/search/__tests__/route.test.ts
Coverage: 100% Statements, 95.83% Branches, 100% Functions, 100% Lines
2. /api/products/search/suggestions - Search Suggestions
File: src/app/api/products/search/suggestions/route.ts
Test File: src/app/api/products/search/suggestions/__tests__/route.test.ts
Coverage: 100% Statements, 100% Branches, 100% Functions, 100% Lines
Test Coverage Summary
Combined Results
--------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
--------------------|---------|----------|---------|---------|-------------------
All files | 100 | 96.77 | 100 | 100 |
search | 100 | 95.83 | 100 | 100 |
route.ts | 100 | 95.83 | 100 | 100 | 40
search/suggestions | 100 | 100 | 100 | 100 |
route.ts | 100 | 100 | 100 | 100 |
--------------------|---------|----------|---------|---------|-------------------
Test Suites: 2 passed, 2 total
Tests: 45 passed, 45 total
Snapshots: 0 total
Test Categories
Main Search Route (/api/products/search)
1. Query Validation (3 tests)
- ✅ Returns empty results when query is missing
- ✅ Returns empty results when query is too short (1 character)
- ✅ Accepts query with exactly 2 characters (minimum length)
2. Successful Search (7 tests)
- ✅ Returns products matching title
- ✅ Returns products matching description
- ✅ Returns products matching category
- ✅ Limits results to 10 items
- ✅ Sorts results by title ascending
- ✅ Handles case-insensitive search
- ✅ Trims whitespace from query
3. Result Transformation (7 tests)
- ✅ Includes all required fields in results
- ✅ Calculates average rating correctly
- ✅ Handles products with no reviews
- ✅ Uses thumbnailUrl when available
- ✅ Falls back to url when thumbnailUrl is not available
- ✅ Sets thumbnail to null when no images exist
- ✅ Handles null descriptions properly
4. Caching (3 tests)
- ✅ Uses cache key based on normalized query
- ✅ Normalizes query for cache (lowercase and trimmed)
- ✅ Returns cached results when available
5. Rate Limiting (3 tests)
- ✅ Returns 429 when rate limit exceeded (100 requests)
- ✅ Includes rate limit headers in 429 response
- ✅ Rate limits per IP address
6. Performance Tracking (2 tests)
- ✅ Measures API performance on success
- ✅ Measures API performance on error
7. Empty Results (2 tests)
- ✅ Returns empty array when no products match
- ✅ Returns empty array for special characters query
8. Error Handling (3 tests)
- ✅ Returns 500 on database error
- ✅ Returns 500 on cache error
- ✅ Handles malformed product data gracefully
9. Security Headers (2 tests)
- ✅ Adds security headers to successful response
- ✅ Adds security headers to error response
10. Query Parameter Edge Cases (3 tests)
- ✅ Handles URL-encoded query parameters
- ✅ Handles query with numbers
- ✅ Handles very long query strings
11. Multiple Products Scenarios (3 tests)
- ✅ Handles products with different image configurations
- ✅ Handles products with varying review counts
- ✅ Respects the 10 result limit when more products exist
Total Tests: 37
Suggestions Route (/api/products/search/suggestions)
1. Query Validation (2 tests)
- ✅ Returns empty array when query is missing
- ✅ Returns empty array when query is too short
2. Successful Search (4 tests)
- ✅ Returns suggestions for valid query
- ✅ Respects custom limit parameter
- ✅ Uses default limit of 10
- ✅ Handles exact 2-character query
3. Empty Results (1 test)
- ✅ Returns empty array when no suggestions found
4. Error Handling (1 test)
- ✅ Returns 500 on service error
Total Tests: 8
Mock Strategy
Mocked Dependencies
Main Search Route
@/lib/prisma- Database client@/lib/security-headers- Security headers@/lib/logger- Error logging@/lib/performance- Performance tracking@/lib/cache- Caching layer@/lib/http-cache- HTTP cache headers
Suggestions Route
@/lib/search- Search utilities (getSearchSuggestions)@/lib/security-headers- Security headers@/lib/logger- Error logging
Mock Data Structure
{
id: 1,
title: "iPhone 15",
description: "Latest iPhone model",
price: 999,
discountedPrice: 899,
images: [
{
url: "/images/iphone15.jpg",
thumbnailUrl: "/images/iphone15-thumb.jpg",
}
],
category: {
id: 1,
title: "Electronics",
},
reviews: [{ rating: 5 }, { rating: 4 }]
}
Key Features Tested
1. Search Functionality
- Multi-field search (title, description, category)
- Query normalization (lowercase, trimmed)
- Minimum query length enforcement (2 characters)
- Result limiting (10 items max)
- Alphabetical sorting
2. Data Transformation
- Average rating calculation
- Review count aggregation
- Image fallback logic (thumbnail → url → null)
- Category data inclusion
3. Performance Optimization
- Redis caching with normalized keys
- Cache TTL management
- Performance measurement tracking
- HTTP cache headers
4. Security & Rate Limiting
- Per-IP rate limiting (100 requests per window)
- Security headers on all responses
- Rate limit headers in 429 responses
- Error information sanitization
5. Error Handling
- Database error recovery
- Cache error handling
- Malformed data detection
- Graceful degradation
Test Utilities Used
From @/test-utils/api-test-helpers
createMockRequest()- Create mock Next.js requestsparseJsonResponse()- Parse JSON responses- Rate limit clearing utilities
From @/lib/rate-limit
clearRateLimit()- Reset rate limits between tests
Edge Cases Covered
-
Query Validation
- Empty queries
- Single character queries
- Very long queries (1000+ chars)
- Special characters
- URL-encoded parameters
- Numeric queries
- Whitespace handling
-
Product Data Variations
- Products with thumbnails
- Products without thumbnails (fallback to url)
- Products without images
- Products with no reviews
- Products with varying review counts
- Null descriptions
-
Error Scenarios
- Database connection failures
- Cache errors
- Malformed product data
- Service errors
-
Rate Limiting
- Exceeding request limit
- Per-IP isolation
- Rate limit header inclusion
Performance Considerations
Optimizations Tested
- ✅ Caching with normalized keys
- ✅ Result limiting (10 items)
- ✅ Efficient Prisma queries
- ✅ Performance measurement
- ✅ HTTP cache headers
Metrics Tracked
- API response time
- Cache hit/miss rates
- Rate limit consumption
- Error rates
Coverage Analysis
Lines Not Covered
- Line 40 in
route.ts: Retry-After header conditional (only set in specific rate limit scenarios)
Why 95.83% Branch Coverage?
The uncovered branch is a defensive check for the Retry-After header that only triggers in specific rate limit timing scenarios that are difficult to test deterministically.
Integration Points
Services Used
- Prisma - Database queries
- Redis Cache - Result caching
- Rate Limiter - Request throttling
- Logger - Error tracking
- Performance Monitor - Metrics collection
- Security Headers - Response hardening
Related Search Functionality
getSearchSuggestions()in@/lib/search- Search term tracking (analytics)
- Cache key generation
- Result normalization
Running the Tests
Individual Tests
# Main search route
npm test -- src/app/api/products/search/__tests__/route.test.ts --coverage
# Suggestions route
npm test -- src/app/api/products/search/suggestions/__tests__/route.test.ts --coverage
Combined Coverage
npm test -- "src/app/api/products/search" --coverage \
--collectCoverageFrom="src/app/api/products/search/**/*.ts" \
--collectCoverageFrom="!src/app/api/products/search/**/*.test.ts"
Future Enhancements
Potential Additional Tests
-
Integration Tests
- Test with real database (test environment)
- Test cache integration with Redis
- Test rate limiting across multiple requests
-
Performance Tests
- Load testing for search endpoint
- Cache effectiveness measurement
- Query optimization validation
-
E2E Tests
- User search flow
- Search suggestions workflow
- Search result interactions
-
Additional Edge Cases
- Unicode and special character handling
- SQL injection prevention
- XSS prevention in search queries
- Concurrent request handling
Related Documentation
- PLAN_29_TESTING_COVERAGE.md
- API Documentation
- Performance Optimization
Conclusion
The products search and suggestions API tests provide comprehensive coverage of:
- ✅ All major code paths
- ✅ Error handling scenarios
- ✅ Security features
- ✅ Performance optimizations
- ✅ Edge cases and validation
With 96.77% combined coverage and 45 passing tests, these endpoints are well-tested and production-ready.
Last Updated: November 28, 2025 Maintained By: Development Team (Philip Rehberger)