Test Scenarios
Generated on 2025-12-08 13:52:43
File: backend/tests/repositories/CourseRepository.test.ts
- CourseRepository
- findPublished
- should retrieve published courses
- search
- should search courses by term
- findPublished
File: backend/tests/repositories/LessonRepository.test.ts
- LessonRepository
- createLesson
- should create a new lesson with all fields
- should create lesson with null video_url if not provided
- updateLesson
- should update lesson with generation_prompt field
- should update only generation_prompt field
- should update all fields including generation_prompt
- should handle empty generation_prompt
- should not update generation_prompt if not provided in DTO
- should return null if lesson not found
- should return existing lesson if no updates provided
- updateGenerationPrompt
- should update only the generation_prompt field
- should return null if lesson not found
- findByCourse
- should retrieve lessons for a course
- findAIGeneratedByCourse
- should retrieve only AI-generated lessons
- findPendingContentGeneration
- should retrieve lessons with prompts but no content
- getAllowedFields
- should include generation_prompt in allowed fields
- createLesson
File: backend/tests/repositories/UserRepository.test.ts
- UserRepository
- findAllWithFilters
- should retrieve users without filters
- should filter users by role
- should filter users by profile_completed
- should apply multiple filters
- should apply custom limit and offset
- should order by created_at DESC
- findByCognitoSub
- should find user by cognito sub
- should return null if user not found
- should return null for empty cognito sub
- should handle null cognito sub gracefully
- findByEmail
- should find user by email
- should return null if user not found
- should handle case-sensitive email search
- search
- should search users by name
- should search users by email
- should search by first_name
- should search by last_name
- should apply role filter with search
- should apply profile_completed filter with search
- should apply multiple filters with search
- should handle empty search term
- should handle custom limit and offset
- createUser
- should create a new user
- updateUser
- should update user role
- should update demographic fields
- should update interests array
- should update learning objectives array
- should update preferred learning style
- should update weekly learning hours
- should update profile_completed status
- should update multiple fields at once
- should handle null values for optional fields
- should return current user if no updates provided
- should return null if user not found
- should include updated_at timestamp
- countByRole
- should return count of users by role
- should order results by count DESC
- should return empty array if no users
- should convert string counts to numbers
- getTotalCount
- should return total user count without filters
- should filter by search term
- should filter by role
- should filter by profile_completed
- should apply multiple filters
- should handle zero count
- should convert string count to number
- findByInterest
- should find users by interest
- should use JSONB containment operator
- should handle custom limit and offset
- should order by created_at DESC
- should return empty array if no users found
- getAllowedFields
- should include all user table columns
- findAllWithFilters
File: backend/tests/utils/database.test.ts
- Database Utilities
- healthCheck
- should return true when database is healthy
- should return false when database is unhealthy
- healthCheck
File: backend/tests/utils/recommendation-engine.test.ts
- RecommendationEngine
- getRecommendationsForUser
- should return personalized recommendations for a user
- should exclude already enrolled courses
- should return empty array when no courses available
- should respect the limit parameter
- getPopularCourses
- should return popular courses sorted by enrollment count
- should exclude specified course IDs
- getSimilarCourses
- should return courses in the same category
- should return empty array when source course not found
- should exclude the source course from results
- Custom Weights
- should allow custom recommendation weights
- Edge Cases
- should handle database errors gracefully
- should handle malformed data
- getRecommendationsForUser
File: backend/functions/ai-generation/src/tests/handlers/generate-lesson-prompts.test.ts
- Generate Lesson Prompts Handler
- Happy Path
- should generate lesson prompts for all days in a 7-day course
- should return LessonPromptsResult with all required fields
- should create lesson prompts with correct structure
- should correctly map lesson data from AI response
- should update job status to GENERATING_LESSONS
- should update progress as lessons are generated
- JobId Handling - Direct vs validationResult
- should use jobId directly when passed in event
- should fallback to validationResult.jobId when jobId not directly passed
- should throw error when jobId is missing from both sources
- Fallback Paths - courseOutline extraction
- should extract outline from wrapped result (ResultSelector format)
- should handle unwrapped outline (backward compatibility)
- should throw when outline extraction fails
- Outline Validation
- should validate extracted outline
- should throw when outline validation fails
- Token Usage Tracking
- should accumulate tokens from outline and all lessons
- should report token usage in progress updates
- Error Handling
- should mark job as failed when Bedrock call fails
- should mark job as failed when JSON parsing fails
- should continue despite validation warnings
- Different Course Durations
- should generate 14 lesson prompts for 14-day course
- should generate 21 lesson prompts for 21-day course
- Lesson Generation Context
- should pass correct day and week information to prompt generator
- should call getDayProgress for each lesson
- should include difficulty level in prompt context
- Progress Calculation
- should calculate progress correctly for 7-day course
- Happy Path
File: backend/functions/ai-generation/src/tests/handlers/generate-outline.test.ts
- Generate Outline Handler
- Happy Path
- should return data in Step Functions ResultSelector format
- should return correct outline structure with all required fields
- should include tokensUsed from Bedrock response
- should update job status to GENERATING_OUTLINE at start
- should update job progress to 30% after generating outline
- should invoke Bedrock with correct parameters
- should call getCourseOutlinePrompt with courseInput
- Validation Warnings
- should continue even when validation has warnings
- should log validation warnings but not throw
- Error Handling
- should mark job as failed when Bedrock call fails
- should mark job as failed when JSON parsing fails
- should propagate error after marking job failed
- should attempt to mark job failed even when it throws
- Edge Cases
- should handle empty curriculum array in response
- should handle missing optional fields in courseInput
- should handle 14-day course duration
- should handle 21-day course duration
- should include jobId in the outline result
- Token Usage Tracking
- should track tokens from Bedrock response
- should update job with token count after generation
- Result Structure for Step Functions
- should return GenerateOutlineResult type structure
- should spread course outline properties into outline field
- Happy Path
File: backend/functions/ai-generation/src/tests/handlers/poll-video-status.test.ts
- Poll Video Status Handler
- Happy Path - Video Status Transitions
- should return pending status when video is still processing
- should return processing status with incremented poll count
- should return completed status with video URL
- should return failed status with error message from HeyGen
- Poll Count Management
- should default pollCount to 0 when not provided
- should increment pollCount on each invocation
- should return timeout error when max poll count is reached
- should return timeout error when poll count exceeds max
- should still poll when pollCount is one below max
- Error Handling
- should handle API errors gracefully
- should handle non-Error exceptions
- should handle unknown errors
- should handle network errors
- should handle timeout errors
- Event Validation
- should handle event with all required fields
- should preserve videoId and courseId in result
- Video URL Handling
- should return videoUrl when status is completed
- should not include videoUrl when status is pending
- should not include videoUrl when status is processing
- should not include videoUrl when status is failed
- Different Video ID and Course ID Combinations
- should handle long video IDs
- should handle UUID-formatted IDs
- Timeout Behavior
- should timeout after 20 polls (10 minutes)
- should not timeout at exactly 19 polls
- Input Validation - Invalid videoId
- should return failed status when videoId is empty string
- should return failed status when videoId is whitespace only
- should return failed status when videoId is null
- should return failed status when videoId is undefined
- should return failed status when videoId contains only tabs
- should return failed status when videoId contains only newlines
- Input Validation - Invalid courseId
- should return failed status when courseId is not a valid UUID
- should return failed status when courseId is empty string
- should return failed status when courseId is null
- should return failed status when courseId has incorrect UUID format (too short)
- should return failed status when courseId has incorrect UUID format (invalid characters)
- should return failed status when courseId has incorrect UUID format (missing dashes)
- should return failed status when courseId has incorrect dash positions
- should accept valid UUID in uppercase
- should accept valid UUID in lowercase
- should accept valid UUID in mixed case
- Input Validation - Multiple Invalid Inputs
- should validate videoId first before courseId
- should validate courseId when videoId is valid
- should increment pollCount even on validation failure
- Edge Cases
- should handle empty error from HeyGen
- should handle status with video_url as null
- should handle pollCount of 0
- should handle negative pollCount (edge case)
- should handle videoId with leading/trailing valid characters after trimming
- Successful Video Generation Scenarios
- should handle immediate completion (poll count 0)
- should handle completion after multiple polls
- Happy Path - Video Status Transitions
File: backend/functions/ai-generation/src/tests/handlers/save-course.test.ts
- Save Course Handler
- updateStatus Action
- should update status with GENERATING_OUTLINE
- should update status with GENERATING_LESSONS
- should update status with GENERATING_VIDEO
- should update status with SAVING
- should throw error with missing jobId
- should throw error with missing status
- should throw error with invalid status value
- should throw error with status not in VALID_UPDATE_STATUSES
- should verify correct progress values for all valid statuses
- handleError Action
- should handle error with valid Error and Cause fields
- should handle error with Error field when Cause is missing
- should throw error with missing jobId
- should throw error with missing error object
- should not throw even if markJobFailed fails
- should return error result structure correctly
- saveCourse Action (Default)
- should save course with valid wrapped course outline and lesson prompts
- should throw error with missing jobId in validationResult
- should throw error with invalid course outline structure (missing title)
- should throw error with invalid course outline structure (missing description)
- should throw error with missing curriculum array
- should throw error with missing lessons array
- should throw error with lesson missing title
- should throw error with lesson missing generationPrompt
- should throw error with lesson missing day number
- should calculate quality score correctly
- should calculate token usage from outline and lessons
- should calculate cost using input/output token split
- should create course with correct metadata
- should create all lessons in batch
- should handle video generation data when provided
- should handle missing video generation data
- should store job result after successful save
- should mark job as failed on error
- should handle jobId from event root (Step Functions pattern)
- should sanitize course title before saving
- should validate metadata before saving
- Category Resolution
- should accept valid UUID as category_id
- should resolve category slug to UUID
- should throw descriptive error for invalid category slug
- should throw descriptive error for numeric string category ID
- should handle category lookup with all valid slug formats
- should sanitize category_id before lookup to prevent SQL injection
- Edge Cases
- should handle zero tokens in courseOutline
- should handle zero tokens in lessonPrompts
- should handle missing tokensUsed in wrapped objects
- should handle backward compatible unwrapped format
- should handle quality score edge cases
- updateStatus Action
File: backend/functions/ai-generation/src/tests/handlers/start-generation.test.ts
- Start Generation Handler
- Basic Request Handling
- should handle OPTIONS preflight request
- should return 401 if no admin user ID found
- should return 400 for invalid JSON in request body
- Request Validation
- should return 400 if courseInput is missing
- should return 400 if title is missing
- should return 400 if category_id is missing
- should return 400 if duration_days is invalid
- should accept valid durations (7, 14, 21)
- PDF Reference Handling - Valid Cases
- should save PDF reference when provided with valid data
- should proceed without PDF reference when not provided
- PDF Reference Handling - Validation Errors
- should return 400 when PDF has invalid base64 content
- should return 400 when PDF has invalid PDF header
- PDF Reference Handling - Infrastructure Errors
- should return 500 when PDF save fails due to database error
- should return 500 when PDF save fails due to connection error
- should not start Step Functions execution if PDF save fails
- Step Functions Integration
- should start Step Functions execution with correct parameters
- should update job status after Step Functions execution starts
- should return 500 if STEP_FUNCTIONS_ARN is not configured
- should handle Step Functions invocation failure
- Response Format
- should return correct response format for successful generation
- should include appropriate message for async generation
- should include appropriate message for sync generation
- Edge Cases
- should handle missing options (use defaults)
- should handle optional course input fields
- should handle large PDF files
- Basic Request Handling
File: backend/functions/ai-generation/src/tests/handlers/update-course-video.test.ts
- Update Course Video Handler
- Happy Path - Successful Updates
- should update course with completed video URL
- should update course with failed status
- should set videoUrl to null when not provided
- should update timestamp to current time
- should return updated course data from database
- Input Validation - Invalid courseId
- should return error when courseId is empty string
- should return error when courseId is null
- should return error when courseId is undefined
- should return error when courseId is not a valid UUID
- should return error when courseId has incorrect UUID format (too short)
- should return error when courseId has incorrect UUID format (invalid characters)
- should return error when courseId has incorrect UUID format (missing dashes)
- should accept valid UUID in uppercase
- should accept valid UUID in lowercase
- Input Validation - Invalid videoStatus
- should return error when videoStatus is empty string
- should return error when videoStatus is null
- should return error when videoStatus is undefined
- should return error when videoStatus is PENDING (invalid)
- should return error when videoStatus is PROCESSING (invalid)
- should return error when videoStatus is IN_PROGRESS (invalid)
- should return error when videoStatus is lowercase completed
- should return error when videoStatus is random string
- should accept COMPLETED status
- should accept FAILED status
- Input Validation - Invalid videoUrl
- should sanitize non-HTTPS URL to null and log warning
- should sanitize untrusted domain URL to null
- should sanitize malformed URL to null
- should sanitize FTP URL to null
- should accept valid HTTPS URL from heygen.com
- should accept valid HTTPS URL from subdomain of heygen.com
- should accept valid HTTPS URL from cloudfront.net
- should accept valid HTTPS URL from amazonaws.com
- should accept valid HTTPS URL with query parameters
- should allow empty videoUrl with failed status
- should reject URL from similar but different domain (heygen.co)
- should reject URL with heygen.com in path but different domain
- Error Handling - Course Not Found
- should return error when course does not exist
- should not return videoUrl when course not found
- Error Handling - Database Errors
- should handle database connection errors
- should handle database query syntax errors
- should handle unknown database errors
- should handle non-Error exceptions
- should handle null exceptions
- SQL Query Validation
- should update correct columns in database
- should return specified columns from database
- Different Video URL Formats
- should handle standard HTTPS URLs
- should handle CDN URLs
- should handle URLs with query parameters
- should handle very long URLs
- Different Course ID Formats
- should handle UUID-formatted course IDs
- should reject short course IDs that are not valid UUIDs
- Video Status Values
- should handle COMPLETED status
- should handle FAILED status
- Result Structure Validation
- should return all required fields on success
- should return all required fields on failure
- should not include error field on success
- Edge Cases
- should handle empty string as videoUrl (converts to null)
- should handle undefined videoUrl (converts to null)
- should preserve original event courseId and videoStatus in error result
- Happy Path - Successful Updates
File: backend/functions/ai-generation/src/tests/handlers/validate-input.test.ts
- Validate Input Handler
- Valid Input
- should validate correct course input
- should create job record with correct parameters
- should update job status to VALIDATING
- should handle all valid duration options
- should handle all valid difficulty levels
- should handle all valid tone options
- Invalid Input - Title
- should reject missing title
- should reject title that is too short
- should reject title that is too long
- should accept title at maximum length (200 chars)
- Invalid Input - Category
- should reject missing category
- Invalid Input - Duration
- should reject invalid duration (not 7, 14, or 21)
- should reject zero duration
- Invalid Input - Difficulty Level
- should reject invalid difficulty level
- Invalid Input - Tone
- should reject invalid tone
- Invalid Input - Learning Objectives
- should reject non-array learning objectives
- should accept empty learning objectives array
- Invalid Input - Reference Materials
- should reject non-array reference materials
- should accept empty reference materials array
- Multiple Validation Errors
- should return all validation errors at once
- Token Estimation
- should estimate tokens for course generation
- should estimate more tokens for longer courses
- Cost Calculation
- should calculate estimated cost
- should use 30/70 input/output token split for cost calculation
- Job Creation on Validation Failure
- should create job record even when validation fails
- Error Handling
- should propagate database errors
- Valid Input
File: backend/functions/ai-generation/src/tests/prompts/course-outline-prompt.test.ts
- Course Outline Prompt
- getCourseOutlinePrompt
- should generate prompt with all required fields
- should include learning objectives when provided
- should include reference materials when provided
- should use default values when optional fields are missing
- should include 7-day curriculum structure guide
- should include 14-day curriculum structure guide
- should include 21-day curriculum structure guide
- should handle empty learning objectives array
- should handle empty reference materials array
- should include JSON structure requirements
- should include guidelines for course creation
- should handle advanced difficulty level
- should handle professional tone
- validateCourseOutline
- should validate a correct course outline
- should reject null input
- should reject undefined input
- should reject non-object input
- should reject missing title
- should reject title that is too short
- should reject non-string title
- should reject missing description
- should reject description that is too short
- should reject non-string description
- should reject missing whatYouWillLearn
- should reject non-array whatYouWillLearn
- should reject whatYouWillLearn with too few items
- should reject missing requirements
- should reject non-array requirements
- should reject requirements with too few items
- should reject missing instructor
- should reject non-object instructor
- should reject instructor missing name
- should reject instructor missing title
- should reject instructor missing avatar
- should reject missing curriculum
- should reject non-array curriculum
- should reject empty curriculum
- should return multiple errors for multiple issues
- getCourseOutlinePrompt
File: backend/functions/ai-generation/src/tests/prompts/lesson-prompts-prompt.test.ts
- Lesson Prompts Prompt
- getLessonPromptGenerationPrompt
- should generate prompt with all required context
- should include curriculum context
- should include additional context when provided
- should not include additional context section when not provided
- should include specific guidance for first lesson (day 1)
- should include specific guidance for last lesson
- should include guidance for start of new week
- should include guidance for middle lessons
- should calculate progress percentage correctly
- should include progress descriptions
- should handle multiple curriculum weeks
- should include JSON output requirements
- should include course guidelines
- should handle intermediate difficulty
- should handle end progress position
- validateLessonPrompt
- should validate a correct lesson prompt
- should reject null input
- should reject undefined input
- should reject non-object input
- should reject missing title
- should reject title that is too short
- should reject non-string title
- should reject missing estimatedDuration
- should reject non-number estimatedDuration
- should reject estimatedDuration less than 5
- should reject estimatedDuration greater than 60
- should reject missing contentGenerationPrompt
- should reject contentGenerationPrompt that is too short
- should reject non-string contentGenerationPrompt
- should reject missing actionItemsHint
- should reject non-string actionItemsHint
- should reject missing keyTakeawaysHint
- should reject non-string keyTakeawaysHint
- should return multiple errors for multiple issues
- getDayProgress
- should return
- should return
- should return
- should handle 14-day courses correctly
- should handle edge cases at boundaries
- getLessonPromptGenerationPrompt
File: backend/functions/ai-generation/src/tests/prompts/video-script-prompt.test.ts
- Video Script Prompt
- getVideoScriptPrompt
- should generate prompt with all required information
- should include all learning objectives
- should include script structure requirements
- should include timing guidelines
- should include tone guidelines
- should handle 14-day duration
- should handle 21-day duration
- should handle empty whatYouWillLearn array
- should format learning objectives as bullet list
- should include format instructions
- validateVideoScript
- should validate a correct video script
- should reject missing script
- should reject null script
- should reject undefined script
- should reject non-string script
- should reject script that is too short
- should reject script that is too long
- should accept script with exactly 100 words
- should accept script with exactly 300 words
- should count words correctly with multiple spaces
- cleanVideoScript
- should trim whitespace from script
- should normalize line breaks
- should remove multiple consecutive line breaks
- should normalize spacing around PAUSE markers
- should handle multiple PAUSE markers
- should clean up extra spaces
- should handle PAUSE markers case-insensitively
- should handle empty script
- should handle script with only whitespace
- should handle complex script with all issues
- estimateVideoDuration
- should estimate duration for 150 words (~60 seconds)
- should estimate duration for 300 words (~120 seconds)
- should add 1 second per PAUSE marker
- should handle script with no pauses
- should handle very short script
- should handle script with many pauses
- should round to nearest second
- should handle empty script
- should handle PAUSE in different cases
- getVideoScriptPrompt
File: backend/functions/ai-generation/src/tests/services/bedrock-client.test.ts
- Bedrock Client
- invokeClaudeModel
- should invoke Bedrock model with correct parameters
- should use default maxTokens when not provided
- should use default temperature when not provided
- should handle missing usage data in response
- should propagate Bedrock API errors
- should use environment variable for model ID
- should handle temperature of 0
- should handle temperature of 1
- parseAIResponse
- should parse valid JSON response
- should parse JSON with markdown code blocks (
- should parse JSON with generic markdown code blocks (
- should handle extra whitespace
- should parse nested JSON objects
- should parse JSON arrays
- should throw error for invalid JSON
- should throw error for incomplete JSON
- should handle empty string
- should handle code block without closing marker
- should parse JSON with special characters
- should handle unescaped newlines in string values
- should handle unescaped tabs in string values
- should handle multiple control characters in string values
- should handle control characters in nested JSON
- should handle control characters in arrays
- should handle form feed and other control characters
- should handle mixed escaped and unescaped control characters
- should handle typical AI lesson generation response with control characters
- sanitizeJsonString
- should escape unescaped newlines in string values
- should escape unescaped tabs in string values
- should escape carriage returns in string values
- should escape form feeds in string values
- should escape backspaces in string values
- should handle multiple control characters
- should not modify already escaped sequences
- should not modify content outside string values
- should handle multiple string fields
- should handle nested objects
- should handle arrays of strings
- should escape rare control characters using unicode notation
- should handle empty strings
- should preserve valid JSON structure
- estimateTokens
- should estimate tokens for short text
- should estimate tokens for longer text
- should return 1 for empty string
- should handle very long text
- should estimate consistently for same text
- should handle text with special characters
- should handle text with newlines
- calculateCost
- should calculate cost for input and output tokens
- should calculate cost for zero tokens
- should calculate cost for only input tokens
- should calculate cost for only output tokens
- should handle large token counts
- should be more expensive for output tokens than input
- should handle fractional token counts
- should calculate typical course generation cost
- getModelId
- should return default model ID when env var not set
- should return custom model ID from environment variable
- should handle empty string in environment variable
- invokeClaudeModel
File: backend/functions/ai-generation/src/tests/services/generation-job-service.test.ts
- Generation Job Service
- createGenerationJob
- should create a new generation job
- should serialize input params as JSON
- should handle database errors
- updateJobStatus
- should update job status and progress
- should set started_at for first generation step
- should set completed_at for COMPLETED status
- should update with course ID when provided
- should update with quality score when provided
- should update with tokens used when provided
- should update with error message when provided
- should update with execution ARN when provided
- should update with model used when provided
- should handle multiple additional data fields
- getJobStatus
- should retrieve job status by ID
- should return null when job not found
- should parse input_params JSON string
- should handle input_params already as object
- getJobsByAdmin
- should retrieve jobs for an admin user
- should use default limit of 20
- should use custom limit and offset
- should return empty array when no jobs found
- markJobFailed
- should mark job as failed with error message
- getPendingJobs
- should retrieve pending jobs
- should use default limit of 10
- should use custom limit
- should only get jobs from last hour
- storeJobResult
- should store generation result in job record
- should serialize complex results as JSON
- createGenerationJob
File: backend/functions/ai-generation/src/tests/services/heygen-client.test.ts
- HeyGen Client
- triggerVideoGeneration
- should trigger video generation with correct parameters
- should use default avatar and voice when not provided
- should use environment variable defaults when available
- should set correct video dimensions
- should handle API error response
- should handle API error with 500 status
- should handle response without data wrapper
- should cache configuration between calls
- should throw error when HEYGEN_SECRET_ARN not set
- getVideoStatus
- should retrieve video status
- should handle pending status
- should handle processing status
- should handle failed status with error
- should handle API error
- should default to pending status when missing
- getAvailableAvatars
- should retrieve available avatars
- should return empty array when no avatars
- should handle API error
- getAvailableVoices
- should retrieve available voices
- should return empty array when no voices
- should handle API error
- clearHeyGenConfigCache
- should clear cache and force config refresh
- triggerVideoGeneration
File: backend/functions/ai-generation/src/tests/services/pdf-reference-service.test.ts
- PDF Reference Service
- isValidBase64
- should return true for valid base64 string
- should return true for base64 with padding
- should return false for invalid base64 characters
- should return false for empty string
- should return false for null/undefined
- should return false for string with wrong length
- isValidPdfContent
- should return true for valid PDF content
- should return false for non-PDF content
- should return false for invalid base64
- should return false for empty string
- savePdfReference
- should save a valid PDF reference document
- should throw error for invalid base64 content
- should throw error for non-PDF content
- should handle database errors
- should catch table not found error (missing migration)
- should handle empty file content validation
- should handle large PDF files
- should handle special characters in file names
- should handle Unicode characters in file names
- should validate PDF magic number for different PDF versions
- linkPdfToCourse
- should link a PDF document to a course
- should handle non-existent document ID gracefully
- should handle database errors during linking
- linkPdfsToCourseTransaction
- should link multiple PDFs to a course in a transaction
- should return 0 for empty document array
- should count only successfully linked documents
- getPdfReferencesByCourse
- should retrieve PDF references for a course
- should return empty array when no documents found
- getPdfReferencesByJob
- should retrieve PDF references for a generation job
- getPdfReferenceById
- should retrieve a PDF reference by ID
- should return null when document not found
- deletePdfReference
- should delete a PDF reference by ID
- should handle deletion of non-existent document gracefully
- should handle database errors during deletion
- Edge Cases and Error Scenarios
- Base64 validation edge cases
- should reject base64 with spaces
- should reject base64 with newlines
- should reject base64 with tabs
- should handle base64 with correct padding
- should handle non-string types
- PDF content validation edge cases
- should accept different PDF versions
- should reject content with partial PDF header
- should reject content with incorrect header
- Database error scenarios
- should handle connection pool exhaustion
- should handle unique constraint violation
- should handle SQL syntax errors
- Concurrent operations
- should handle multiple simultaneous saves
- Transaction rollback scenarios
- should rollback on transaction error
- should handle transaction with client query failure
- File size edge cases
- should handle zero-byte files
- should handle extremely large files
- Filename edge cases
- should handle very long filenames
- should handle filenames with path traversal attempts
- should handle filenames with null bytes
- Base64 validation edge cases
- isValidBase64
File: backend/functions/ai-generation/src/tests/utils/validation.test.ts
- Validation Utils
- validateAndSanitizeCourseMetadata
- Valid Metadata
- should validate and sanitize valid metadata
- should accept minimal required metadata
- should accept null optional fields
- should handle valid quality_score boundary values
- should handle maximum array lengths
- should return metadata assignable to Record<string, unknown>
- should work in JSON.stringify context
- Invalid Metadata - Required Fields
- should reject metadata missing ai_generated
- should reject metadata missing model_used
- should reject metadata missing generation_timestamp
- Invalid Metadata - Type Validation
- should reject non-boolean ai_generated
- should convert non-string model_used to string during sanitization
- should reject non-array whatYouWillLearn
- should reject non-number quality_score
- should reject non-integer tokens_used
- Invalid Metadata - Length Constraints
- should reject model_used exceeding max length
- should reject whatYouWillLearn with too many items
- should reject whatYouWillLearn items exceeding max length
- should reject intro_video_script exceeding max length
- Invalid Metadata - Value Constraints
- should reject quality_score less than 0
- should reject quality_score greater than 1
- should reject negative tokens_used
- Invalid Metadata - Instructor Object
- should reject instructor missing required name
- should reject instructor missing required title
- should reject instructor name exceeding max length
- Sanitization
- should sanitize HTML in string fields
- should not mutate the original input
- should trim whitespace from strings
- Integration with Database Usage
- should produce metadata compatible with JSON.stringify for database storage
- Valid Metadata
- validateAndSanitizeCourseInput
- Valid Input
- should validate correct course input
- should accept minimal required input
- should handle all valid duration options
- should sanitize learning objectives array
- should sanitize reference materials array
- Invalid Input
- should reject title too short
- should reject invalid duration
- should reject invalid difficulty level
- should reject non-array learning objectives
- Valid Input
- sanitizeString
- should remove HTML tags
- should trim whitespace
- should handle empty string
- should handle non-string input
- sanitizeStringArray
- should sanitize all strings in array
- should filter out non-string items
- should return empty array for non-array input
- should handle empty array
- validateAndSanitizeCourseMetadata
File: backend/functions/analytics/src/tests/index.test.ts
- Analytics Lambda Handler
- CORS Headers
- should include CORS headers in all responses
- should include CORS headers in error responses
- OPTIONS request
- should return 200 for CORS preflight
- should return CORS headers for OPTIONS on any path
- Authentication
- should return 401 when requestContext is missing
- should return 401 when authorizer is missing
- should return 401 when claims are missing
- should return 401 when sub claim is missing
- should return 401 when user is not found in database
- should return 401 when user object has no id
- HTTP Method Validation
- should return 405 for POST request
- should return 405 for PUT request
- should return 405 for DELETE request
- should return 405 for PATCH request
- GET /analytics
- should return comprehensive analytics data for authenticated user
- should use default 30 days when days parameter is missing
- should handle custom days parameter
- should handle minimum valid days parameter (1)
- should handle maximum valid days parameter (365)
- should return 400 for days parameter below minimum (0)
- should return 400 for days parameter above maximum (366)
- should return 400 for negative days parameter
- should return 400 for non-numeric days parameter
- should return 400 for decimal days parameter
- should handle empty analytics data gracefully
- should return 500 when getUserAnalytics throws error
- GET /analytics/activity
- should return activity data with default 30 days
- should respect custom days parameter for activity
- should return 401 for unauthenticated user
- should return 400 for invalid days parameter
- should handle empty activity data
- should return 500 when getActivityData throws error
- should handle path ending with /activity
- GET /analytics/streaks
- should return streak data for authenticated user
- should return 401 for unauthenticated user
- should handle zero streaks data
- should return 500 when getStreakData throws error
- should handle path ending with /streaks
- Error Handling
- should return 500 on database connection error
- should handle non-Error exceptions gracefully
- should handle undefined exceptions
- should handle repository instantiation errors
- Path Routing
- should route to analytics endpoint for base path
- should route to analytics endpoint for root path
- should handle paths with stage prefix
- Edge Cases
- should handle empty path string and route to default analytics
- should handle queryStringParameters as null and use default days
- should handle queryStringParameters as undefined and use default days
- should handle empty queryStringParameters object and use default days
- CORS Headers
File: backend/functions/categories/src/tests/index.test.ts
- Categories Lambda Handler
- GET /categories - List All Categories
- should return all categories ordered by name
- should handle empty category list
- should include null values in response
- should handle database errors gracefully
- GET /categories/:id - Get Single Category
- should return a single category when ID is provided
- should return 404 when category is not found
- should handle UUID format category IDs
- should handle database errors when fetching single category
- OPTIONS - CORS Support
- should handle OPTIONS requests for CORS preflight
- should not execute database queries for OPTIONS requests
- should include proper CORS headers in OPTIONS response
- Unsupported HTTP Methods
- should return 405 for POST requests
- should return 405 for PUT requests
- should return 405 for DELETE requests
- should return 405 for PATCH requests
- should not execute database queries for unsupported methods
- Response Format and Headers
- should include CORS headers in all successful responses
- should include CORS headers in error responses
- should return valid JSON in response body
- should set correct Content-Type header
- Error Handling
- should handle AppError instances correctly
- should handle null query result
- should handle undefined query result
- should log errors to console
- should handle query timeout errors
- should handle network errors
- Edge Cases
- should handle very long category names
- should handle categories with special characters in names
- should handle categories with very long URLs
- should handle empty query string parameters object
- should handle multiple query parameters with only id being used
- should handle Date objects in created_at field
- Logging
- should log incoming events
- should log errors during request handling
- GET /categories - List All Categories
File: backend/functions/courses/src/tests/index.test.ts
- Courses Lambda Handler
- OPTIONS - CORS Preflight
- should handle OPTIONS requests for CORS with correct headers
- should return empty or minimal body for OPTIONS requests
- GET /courses - List Courses
- Public Access
- should return list of courses for anonymous users
- should respect pagination parameters
- should filter by category
- should search courses by keyword
- should filter by duration
- Admin Access
- should return all courses including drafts for admin users
- Get Single Course
- should return single course when ID is provided
- should return 404 when course not found
- Public Access
- POST /courses - Create Course
- Authentication & Authorization
- should require admin authentication
- should reject non-admin users
- Successful Creation
- should create course with valid data
- Validation
- should return 400 when request body is missing
- Authentication & Authorization
- PUT /courses - Update Course
- Authentication & Authorization
- should require admin authentication
- Successful Update
- should update course with valid data
- should pass authContext to handlePut for audit logging
- should extract adminUserId from authContext.sub
- should log course update with admin user ID
- should handle update when auth context is available
- should return success response with updated course data
- should pass correct parameters to CourseService.updateCourse
- should handle updates from different admin users
- Validation
- should return 400 when ID is missing
- should return 400 when request body is missing
- Authentication & Authorization
- DELETE /courses - Delete Course 🎯
- Authentication & Authorization
- should require admin authentication for DELETE requests
- should reject DELETE requests from non-admin users
- should allow DELETE requests from authenticated admin users
- Successful Deletion
- should successfully delete course with valid ID
- should pass admin user ID for audit logging
- should log deletion with admin user information
- should handle deletion when auth context is available
- should return success response with correct headers
- should handle deletion of course with UUID format ID
- should log successful deletion operations
- Validation
- should return 400 when course ID is missing
- should return 400 when course ID is null
- should return 400 when queryStringParameters is null
- should return 400 when course ID is not a valid UUID format
- should accept valid UUID format for course ID
- Enrollment Check
- should return 409 when course has active enrollments
- should successfully delete course with zero enrollments
- should return 409 with correct message for single enrollment
- Error Handling
- should return 404 when course does not exist
- should handle database errors gracefully
- should handle service layer exceptions
- should log errors for debugging
- Edge Cases
- should handle very long course IDs
- should handle special characters in course ID
- should handle whitespace in course ID
- Concurrent Deletion
- should handle concurrent deletion attempts
- CORS Compliance
- should include CORS headers in successful DELETE response
- should include CORS headers in error responses
- Authentication & Authorization
- Error Handling - General
- should return 405 for unsupported HTTP methods
- should handle unexpected errors in main handler
- should log all incoming events for debugging
- Integration Tests - Complete Workflows
- should handle complete CRUD workflow
- OPTIONS - CORS Preflight
File: backend/functions/enrollments/src/tests/resolveCourseId.test.ts
- resolveCourseId
- UUID handling
- should return UUID as-is when valid UUID is provided
- should handle uppercase UUIDs
- should handle mixed case UUIDs
- Mock numeric ID mapping
- should map mock ID 1 to first course (index 0)
- should map mock ID 2 to second course (index 1)
- should map mock ID 5 to fifth course (index 4)
- should use cache for subsequent calls
- should maintain consistent ordering based on created_at
- Error handling
- should throw error when mock ID exceeds available courses
- should throw error for mock ID 0
- should throw error for negative mock IDs
- should throw error for non-numeric, non-UUID strings
- should throw error for decimal numbers
- should throw error when no courses exist in database
- should throw error when findAll returns null
- Edge cases
- should handle mock ID as string with leading zeros
- should reject invalid UUID formats
- should reject UUID-like strings with invalid characters
- should handle whitespace in input
- should handle empty string
- Cache behavior
- should cache course mappings across multiple calls
- should maintain cache state between different mock IDs
- Boundary conditions
- should handle exactly 1 course in database
- should handle maximum valid mock ID
- should reject mock ID immediately after maximum
- Concurrent access
- should handle concurrent resolveCourseId calls correctly
- UUID handling
File: backend/functions/recommendations/src/tests/index.test.ts
- Recommendations Lambda Handler
- GET /recommendations - Personalized
- should return personalized recommendations for authenticated user
- should respect custom limit parameter
- should return 401 when not authenticated for personalized recommendations
- GET /recommendations - Popular
- should return popular courses without authentication
- GET /recommendations - Similar
- should return similar courses when courseId is provided
- should return 400 when courseId is missing for similar type
- GET /recommendations - Default behavior
- should return personalized for authenticated users by default
- should return popular for anonymous users by default
- Validation
- should return 400 for invalid limit parameter
- should return 400 for limit exceeding maximum
- should return 400 for negative limit
- OPTIONS - CORS
- should handle OPTIONS requests for CORS
- Error Handling
- should handle recommendation engine errors gracefully
- should return 405 for unsupported HTTP methods
- GET /recommendations - Personalized
File: backend/functions/users/src/tests/index.test.ts
- Users Lambda Handler
- Authentication & Authorization
- should require admin authentication for GET requests
- should require admin authentication for PUT requests
- should allow authenticated admin to access endpoints
- GET /users - List Users
- should return all users with default pagination
- should respect custom limit and offset parameters
- should enforce MAX_LIMIT of 100
- should filter by role
- should filter by profile_completed
- should combine multiple filters
- GET /users - Search Users
- should search users by query
- should search with filters and pagination
- GET /users/:id - Get User by ID
- should return user when found
- should return 404 when user not found
- PUT /users/:id - Update User
- should update user with valid data
- should log admin action with full context
- should log before/after changes in audit log
- should return 400 when user ID is missing
- should return 400 when request body is missing
- should return 404 when user not found
- should return 422 for validation errors
- should sanitize string inputs
- OPTIONS - CORS
- should handle OPTIONS requests for CORS
- should not require authentication for OPTIONS
- Error Handling
- should return 500 on database error in GET
- should return 500 on database error in PUT
- should return 405 for unsupported HTTP methods
- should handle malformed JSON in request body
- Response Format
- should include CORS headers in all responses
- should return valid JSON in response body
- Edge Cases
- should handle empty user list
- should handle search with no results
- should handle update with no actual changes
- should handle zero offset and limit
- should handle invalid role filter gracefully
- Authentication & Authorization
File: backend/shared/auth/tests/jwt-validator.test.ts
- JWT Validator
- validateAccessToken
- should validate a valid access token
- should reject an expired token
- should reject a token with invalid signature
- should handle non-Error exceptions
- validateIdToken
- should validate a valid ID token
- should reject an invalid ID token
- extractTokenFromHeader
- should extract token from valid Bearer header
- should return null for missing header
- should return null for empty header
- should return null for header without Bearer prefix
- should return null for header with wrong prefix
- should return null for header with extra parts
- should handle header with only Bearer
- Edge Cases
- should handle verifier creation for different user pools
- should handle tokens with special characters
- validateAccessToken
File: backend/shared/auth/tests/middleware.test.ts
- Authentication Middleware
- authenticateUser
- should authenticate user with valid token
- should fail authentication without token
- should fail authentication with invalid token
- should handle lowercase authorization header
- should parse role correctly
- requireAuth
- should authorize authenticated user
- should reject unauthenticated user
- requireRole
- should authorize user with allowed role
- should authorize user with one of multiple allowed roles
- should reject user without allowed role
- should reject unauthenticated user
- requirePermission
- should authorize user with required permission
- should reject user without required permission
- should allow premium user to view premium courses
- requireAdmin
- should authorize admin user
- should reject non-admin user
- should reject free user
- requirePremium
- should authorize premium user
- should authorize admin user
- should reject free user
- Response Formats
- should return properly formatted unauthorized response
- should return properly formatted forbidden response
- authenticateUser
File: backend/shared/auth/tests/role-checker.test.ts
- Role Checker
- hasPermission
- should return true if user has permission
- should return false if user does not have permission
- should grant admin users all permissions
- hasRole
- should return true if user has one of the allowed roles
- should return false if user does not have any allowed role
- hasMinimumRole
- should return true if user role meets or exceeds minimum
- should return false if user role is below minimum
- isAdmin
- should return true for admin role
- should return false for non-admin roles
- isPremiumOrHigher
- should return true for premium and admin roles
- should return false for free role
- canAccessAdminPanel
- should return true only for admin role
- canManageCourses
- should return true only for admin role
- getPermissionsForRole
- should return correct permissions for each role
- isValidRole
- should return true for valid roles
- should return false for invalid roles
- parseRole
- should parse valid role strings
- should default to FREE for invalid roles
- hasPermission
File: backend/shared/services/tests/CourseService.test.ts
- CourseService
- getCourse
- should return course with stats when found
- should throw NotFoundError when course not found
- getCourses
- search filter
- should search courses by search term with correct total count
- should use custom limit and offset for search
- category filter
- should filter courses by category for non-admin (published only)
- should filter courses by category for admin (all courses)
- should use custom limit and offset for category filter
- duration filter
- should filter courses by duration 7 days with correct total count
- should filter courses by duration 14 days
- should filter courses by duration 21 days
- should throw ValidationError for invalid duration
- default behavior
- should return all courses for admin users with correct total count
- should return only published courses for non-admin users with correct total count
- should return published courses when isAdmin is not specified
- filter precedence
- should prioritize search over category when both provided
- should prioritize category over duration when both provided
- pagination validation
- should use default pagination values
- should throw ValidationError for limit less than 1
- should throw ValidationError for limit greater than 1000
- should throw ValidationError for negative offset
- should accept valid limit at boundary (1)
- should accept valid limit at boundary (1000)
- search filter
- createCourse
- should create a new course with valid 7-day duration
- should create a new course with valid 14-day duration
- should create a new course with valid 21-day duration
- should throw ValidationError for invalid duration
- should throw ValidationError for duration of 0
- updateCourse
- Basic Updates
- should update an existing course
- should throw NotFoundError when course does not exist
- should throw NotFoundError when update returns null
- should validate duration when updating
- should allow updating to valid duration
- should allow updating without duration field
- should throw ValidationError for invalid UUID format
- should accept valid UUID format
- Audit Trail Logging
- should log update activity when adminUserId is provided
- should log update activity with correct metadata structure
- should log with null userId when adminUserId not provided
- should include previous and new status in audit log
- should log activity type as COURSE_UPDATED
- should include all update changes in metadata
- should not fail update if audit logging fails
- should log error with full context when audit logging fails
- should log error with null userId when adminUserId not provided and audit fails
- should get existing course before update for audit comparison
- should handle course with undefined adminUserId gracefully
- Basic Updates
- deleteCourse
- Basic Deletion
- should delete a course with no enrollments
- should throw NotFoundError when course does not exist
- should throw ConflictError when course has active enrollments
- should throw ValidationError for invalid UUID format
- should accept valid UUID format
- Audit Trail Logging
- should log delete activity when adminUserId is provided
- should log delete activity with correct metadata structure
- should log with null userId when adminUserId not provided
- should log activity type as COURSE_DELETED
- should not fail deletion if audit logging fails
- should log error with full context when audit logging fails
- should log error with null userId when adminUserId not provided and audit fails
- should handle undefined adminUserId gracefully
- Basic Deletion
- publishCourse
- should change course status to PUBLISHED
- should throw NotFoundError when course does not exist
- should allow publishing an already published course (idempotent)
- unpublishCourse
- should change course status to DRAFT
- should throw NotFoundError when course does not exist
- should allow unpublishing an already draft course (idempotent)
- getCourse
File: backend/shared/services/tests/EnrollmentService.test.ts
- EnrollmentService
- resolveCourseId
- should return UUID as-is
- should return UUID as-is (case insensitive)
- should map numeric ID to course (1 -> first course)
- should map numeric ID to course (2 -> second course)
- should throw ValidationError when no courses in database
- should throw ValidationError for invalid numeric ID (NaN)
- should throw ValidationError for zero
- should throw ValidationError for negative number
- should throw ValidationError when mock ID exceeds available courses
- should use cached mappings on subsequent calls
- should refresh cache after clearCache is called
- getUserIdFromCognitoSub
- should return user ID for valid cognito sub
- should throw AuthenticationError for empty cognito sub
- should throw NotFoundError when user not found
- checkEnrollment
- should return enrolled: true when user is enrolled
- should return enrolled: false when user is not enrolled
- should resolve mock course IDs before checking enrollment
- getEnrollment
- should return enrollment with progress when found
- should throw NotFoundError when enrollment not found
- getEnrollmentsByUser
- should return paginated enrollments for user
- should use custom limit and offset
- should return empty array when user has no enrollments
- createEnrollment
- should create new enrollment successfully
- should create enrollment without optional payment fields
- should resolve mock course ID before creating enrollment
- should throw AuthenticationError for missing cognito sub
- should throw NotFoundError when user not found
- should throw ConflictError when user is already enrolled
- should throw ValidationError for invalid course ID
- completeEnrollment
- should mark enrollment as completed
- should throw NotFoundError when enrollment not found
- cancelEnrollment
- should cancel enrollment
- should throw NotFoundError when enrollment not found
- clearCache
- should clear the course mapping cache
- should refresh cache after TTL expires
- defensive null check
- should have defensive check after cache initialization block
- resolveCourseId
File: backend/shared/services/tests/LessonService.test.ts
- LessonService
- getLesson
- should return lesson with course info when found
- should throw NotFoundError when lesson not found
- getLessonsByCourse
- should return paginated lessons for a course
- should use default pagination values
- should throw ValidationError for limit less than 1
- should throw ValidationError for limit greater than 1000
- should throw ValidationError for negative offset
- should handle large valid offset
- getAllLessons
- should return all lessons with correct total count
- should use default pagination values
- should throw ValidationError for invalid limit
- should throw ValidationError for negative offset
- canAccessLesson
- unauthenticated users
- should allow access to first lesson (day 1)
- should deny access to non-first lessons
- should deny access when lesson not found
- authenticated users
- should deny access when not enrolled
- should return lesson_not_found when lesson does not exist
- should allow access to first lesson for enrolled users
- should deny access when previous lesson is incomplete (using optimized query)
- should deny access when previous lesson progress exists but not completed
- should allow access when previous lesson is completed
- should allow access when no previous lesson exists (edge case)
- unauthenticated users
- addLockedStatus
- should lock all lessons except first for unauthenticated users
- should lock all lessons except first for unenrolled users
- should unlock lessons based on progress for enrolled users
- should handle all lessons completed
- should sort lessons by day before determining lock status
- createLesson
- should create a new lesson
- updateLesson
- should update an existing lesson
- should throw NotFoundError when lesson does not exist
- should throw NotFoundError when update returns null
- deleteLesson
- should delete a lesson
- should throw NotFoundError when lesson does not exist
- getLesson
File: backend/shared/services/tests/ProgressService.test.ts
- ProgressService
- getUserIdFromCognitoSub
- should return user ID for valid cognito sub
- should throw AuthenticationError for empty cognito sub
- should throw NotFoundError when user not found
- getProgress
- should return progress for specific lesson
- should return null when lesson progress not found
- should return progress for specific course
- should return progress with details for specific course
- should return all progress for user
- should return all progress with details for user
- getCourseSummary
- should return course summary
- should throw ValidationError for missing courseId
- markLessonComplete
- should mark lesson as complete
- should trigger badge check on lesson complete
- should not trigger badge check when lesson not found
- should handle badge check errors gracefully
- markLessonIncomplete
- should mark lesson as incomplete
- should return null when progress record not found
- updateTimeSpent
- should update time spent
- should throw ValidationError for negative time
- should throw ValidationError for NaN time
- should accept zero time
- createOrUpdateProgress
- should mark complete when completed is true
- should mark incomplete when completed is false
- should update time spent when timeSpentSeconds provided
- should create default progress when no options provided
- should create default progress when options is empty
- should prioritize completed over timeSpentSeconds
- deleteProgress
- should delete progress for user and course
- should return 0 when no progress deleted
- should throw ValidationError for missing courseId
- getUserIdFromCognitoSub
File: backend/shared/utils/tests/lambda-auth.test.ts
- Lambda Auth Utilities
- getAuthContext
- unauthenticated requests
- should return null when no authorizer claims exist
- should return null when authorizer is undefined
- should return null when claims is undefined
- should return null when sub is missing from claims
- should return null when user is not found in database
- authenticated requests
- should return auth context for valid authenticated user
- should return correct role for admin user
- should return correct role for premium user
- should call UserRepository with correct cognito sub
- unauthenticated requests
- requireAuth
- should throw AuthenticationError when authContext is null
- should throw AuthenticationError with default message
- should return authContext when it is valid
- should return same reference as input
- requireRole
- when role does not match
- should throw AuthorizationError for wrong role
- should throw AuthorizationError with descriptive message for single role
- should throw AuthorizationError with descriptive message for multiple roles
- should throw for PREMIUM user trying to access ADMIN resource
- when role matches
- should not throw for matching single role
- should not throw when role is in allowed roles list
- should not throw for FREE user accessing FREE resource
- should return void when role matches
- when role does not match
- isAdmin
- should return true for ADMIN role
- should return false for FREE role
- should return false for PREMIUM role
- getUserIdFromEvent (backward compatibility)
- should return null for unauthenticated event
- should return null when user not found
- should return user ID for authenticated user
- should call UserRepository correctly
- Edge Cases
- should handle empty cognito sub string
- should handle null cognito sub
- should return null when requestContext is undefined
- should handle repository throwing an error
- AuthContext Interface
- should have all required properties
- getAuthContext
File: backend/shared/utils/tests/lambda-errors.test.ts
- Lambda Error Classes
- AppError
- should create error with default status code 500
- should create error with custom status code
- should create error with custom status code and error code
- should be an instance of Error
- should have a stack trace
- AuthenticationError
- should create error with default message
- should create error with custom message
- should be an instance of AppError
- should have a stack trace
- AuthorizationError
- should create error with default message
- should create error with custom message
- should be an instance of AppError
- should have a stack trace
- NotFoundError
- should create error with default resource name
- should create error with custom resource name
- should create error with descriptive resource name
- should be an instance of AppError
- should have a stack trace
- ValidationError
- should create error with message only
- should create error with message and details object
- should create error with message and details array
- should create error with message and string details
- should be an instance of AppError
- should have a stack trace
- ConflictError
- should create error with default message
- should create error with custom message
- should be an instance of AppError
- should have a stack trace
- Error HTTP Status Code Mapping
- should have correct status codes for all error types
- Error Code Mapping
- should have correct codes for all error types
- Error Name Property
- should have correct names for all error types
- Error Throwing and Catching
- should be throwable and catchable as Error
- should be throwable and catchable as AppError
- should be catchable by specific error type
- should preserve message when caught
- toJSON Method
- should return correct JSON for AppError
- should use INTERNAL_ERROR as default code
- should return correct JSON for AuthenticationError
- should return correct JSON for AuthorizationError
- should return correct JSON for NotFoundError
- should return correct JSON for ConflictError
- should include details in ValidationError toJSON
- should not include details in ValidationError toJSON when undefined
- should not include details in ValidationError toJSON when null
- AppError
File: backend/shared/utils/tests/lambda-response.test.ts
- Lambda Response Utilities
- DEFAULT_CORS_METHODS constant
- should export default CORS methods
- createResponse
- should return response with correct status code
- should return response with correct body
- should include Content-Type header
- should include CORS headers with default methods
- should accept custom CORS methods parameter
- should accept POST-only CORS methods
- should use default ALLOWED_ORIGIN of * when env variable is not set
- should use ALLOWED_ORIGIN from environment variable
- should handle various status codes
- should handle complex nested objects
- should handle null body
- should handle array body
- should handle string body
- should handle number body
- should handle boolean body
- createSuccessResponse
- should return 200 status code by default
- should accept custom status code
- should accept custom CORS methods
- should use default methods when not specified
- should include success: true in body
- should wrap data correctly
- should include CORS headers
- should handle null data
- should handle array data
- should handle primitive data types
- should handle 201 Created status
- createErrorResponse
- should return 500 status code by default
- should accept custom status code
- should accept custom CORS methods
- should use default methods when not specified
- should include success: false in body
- should include error message
- should include details when provided
- should not include details when not provided
- should include CORS headers
- should handle common HTTP error codes
- should handle array details
- should handle complex details object
- should handle null details by not including them
- should handle undefined details by not including them
- should handle empty object details
- should handle empty string details by not including them
- should handle string details when provided
- should handle details with custom methods
- createOptionsResponse
- should return 200 status code
- should return empty object body
- should include CORS headers with default methods
- should accept custom CORS methods
- should use ALLOWED_ORIGIN from environment
- CORS Methods Customization
- should allow GET-only endpoints
- should allow POST-only endpoints
- should allow read-only endpoints (GET, HEAD)
- should allow all CRUD operations
- CORS Headers Integration
- should have consistent CORS headers across all response types with default methods
- should allow custom methods for all response types
- should all respect ALLOWED_ORIGIN environment variable
- Response Format Backward Compatibility
- createSuccessResponse should match expected success format
- createErrorResponse should match expected error format without details
- createErrorResponse should match expected error format with details
- Index exports
- should export all functions from index
- createErrorFromException
- should convert AuthenticationError to proper response
- should convert AuthorizationError to proper response
- should convert NotFoundError to proper response
- should convert ValidationError with details to proper response
- should convert ValidationError without details to proper response
- should convert generic AppError to proper response
- should convert generic Error to 500 response
- should include CORS headers
- should accept custom CORS methods
- should use INTERNAL_ERROR as default code for AppError without code
- DEFAULT_CORS_METHODS constant
File: backend/shared/utils/tests/user-validation.test.ts
- User Validation
- validateUpdateUserInput
- Valid Input
- should accept valid role update
- should accept all valid roles
- should accept valid gender values
- should accept valid age groups
- should accept valid location data
- should accept valid interests array
- should accept maximum 20 interests
- should accept valid learning objectives
- should accept maximum 20 learning objectives
- should accept valid learning styles
- should accept valid weekly learning hours
- should accept profile_completed boolean
- should accept null for optional fields
- should accept empty string for optional fields
- should accept complete profile update
- should accept partial profile update
- should accept single field update
- should accept maximum length strings
- Invalid Role
- should reject invalid role
- should reject lowercase role
- should reject numeric role
- should reject empty role
- Invalid Gender
- should reject invalid gender
- should reject uppercase gender
- should reject mixed case gender
- should reject numeric gender
- Invalid Age Group
- should reject invalid age group
- should reject age group without hyphen
- should reject numeric age group
- should reject age group with spaces
- Invalid Location Data
- should reject country exceeding max length
- should reject city exceeding max length
- should reject timezone exceeding max length
- should reject non-string country
- should reject non-string city
- should reject non-string timezone
- Invalid Interests
- should reject non-array interests
- should reject interests exceeding maximum count
- should reject interests with non-string items
- should reject interests with items exceeding max length
- should reject interests as object
- should reject interests as number
- should accept interests with empty strings (they are valid strings)
- Invalid Learning Objectives
- should reject non-array learning objectives
- should reject learning objectives exceeding maximum count
- should reject learning objectives with non-string items
- should reject learning objectives with items exceeding max length
- should reject learning objectives as object
- should reject learning objectives with null items
- Invalid Learning Style
- should reject invalid learning style
- should reject uppercase learning style
- should reject mixed case learning style
- should reject numeric learning style
- Invalid Weekly Learning Hours
- should reject non-numeric weekly learning hours
- should reject hours less than 1
- should reject negative hours
- should reject hours greater than 40
- should reject NaN
- should reject Infinity
- should accept decimal hours
- Invalid Profile Completed
- should reject non-boolean profile_completed
- should reject numeric profile_completed
- should reject null profile_completed when explicitly set
- Multiple Validation Errors
- should return all validation errors
- should not stop at first error
- should validate all array constraints
- Edge Cases
- should handle empty input object
- should handle undefined input gracefully
- should handle fields with undefined values
- should validate boundary values for weekly learning hours
- should handle special characters in strings
- should handle unicode in strings
- should handle whitespace-only strings for non-empty allowed fields
- should validate complex realistic profile
- ValidationError Structure
- should return errors with field property
- should return errors with message property
- should return descriptive error messages
- Valid Input
- validateUpdateUserInput
File: frontend/app/admin/tests/page.test.tsx
- AdminPanelPage
- with admin user authenticated
- should render admin panel for authenticated admin
- should display admin welcome message with user name
- should display system health stats
- should display all admin management cards
- should have correct links to admin sections
- should display recent activity section
- should include Header component
- with non-admin user
- should redirect non-admin users to dashboard
- should not render admin panel content for non-admin users
- with unauthenticated user
- should redirect unauthenticated users to signin
- should not render admin panel content for unauthenticated users
- loading state
- should show loading state while checking authentication
- premium user access
- should redirect premium (non-admin) users to dashboard
- with admin user authenticated
File: frontend/app/admin/analytics/tests/page.test.tsx
- AdminAnalyticsPage
- Rendering - Page Structure
- should render the page header
- should render the page description
- should render the Header component with correct props
- should render back to admin panel link
- should render dashboard icon
- Loading State
- should show loading state initially
- should show loading spinner
- should pass loading state to KPICardGrid
- should hide loading state after data loads
- Data Fetching
- should fetch analytics data on mount
- should fetch analytics data with default 30d range
- should pass compare flag to API
- should display KPI cards with data after loading
- should handle API error gracefully
- Date Range Picker
- should render date range picker
- should show default 30d range
- should refetch data when date range changes
- should update date range value when changed
- Tabs Navigation
- should render all 5 tabs
- should show Overview tab as active by default
- should render Overview section by default
- should switch to Users tab when clicked
- should switch to Courses tab when clicked
- should switch to Revenue tab when clicked
- should switch to Engagement tab when clicked
- should highlight active tab
- should not highlight inactive tabs
- Refresh Functionality
- should render refresh button
- should refetch data when refresh button is clicked
- should show refreshing state when refresh is clicked
- should update last updated timestamp after refresh
- Export Functionality
- should render export button
- should call export API when export button is clicked
- should call downloadCSV after successful export
- should show loading state during export
- should disable export button when loading analytics
- should handle export error gracefully
- Last Updated Timestamp
- should display last updated timestamp
- should format timestamp with locale string
- KPI Cards Integration
- should render KPI card grid
- should pass analytics data to KPI cards
- Styling and Layout
- should have gradient background
- should have header section with gradient background
- should have responsive container
- Edge Cases
- should handle null analytics data
- should handle switching tabs multiple times
- should maintain selected tab when refreshing data
- Rendering - Page Structure
File: frontend/app/admin/courses/[id]/edit/tests/page.test.tsx
- EditCoursePage
- Bug Fix: Parallel Fetching of Course and Lessons
- should fetch course and lessons in parallel using Promise.all
- should display loading state while fetching data
- should display course data after successful fetch
- should store lessons in separate state
- Bug Fix: Lessons Tab Count and Display
- should show correct lesson count from lessons state
- should display lessons when switching to lessons tab
- should show zero count when no lessons exist
- should display empty state message when no lessons exist
- should iterate over lessons state instead of course.lessons
- Error Handling
- should display error when course fetch fails
- should display error when lessons fetch fails
- should display error when both fetches fail
- should show back to courses button on error
- should handle non-Error exceptions
- should display course not found error
- Navigation
- should navigate back to courses on cancel
- should navigate back to courses after successful update
- should have back to courses link in header
- Tab Switching
- should switch between overview and lessons tabs
- should highlight active tab
- Course Preview Card
- should display course status badge
- should display course title in header
- should display course duration
- should display truncated course ID
- Course Form Integration
- should pass course data to CourseForm
- should pass isEditing=true to CourseForm
- should call updateCourse on form submission
- Bug Fix: Parallel Fetching of Course and Lessons
File: frontend/app/admin/generate/tests/page.test.tsx
- AIGeneratePage
- Page Rendering
- should render the page with Header component
- should render page header with title and icon
- should render back to admin panel link
- should render with gradient background
- Initial State - Form View
- should render CourseGenerationForm initially
- should not render progress or preview components in form state
- State Transitions
- should transition from form to generating state when generation starts
- should pass correct jobId to GenerationProgress component
- should transition from generating to preview state when generation completes
- should pass correct result data to GeneratedCoursePreview
- should transition back to form state when error occurs
- handleStartOver Function
- should reset to form state when start over is clicked
- should clear jobId and result when starting over
- should allow multiple generation cycles
- Component Integration
- should render all three components at different stages
- should maintain Header component throughout all states
- UI Elements
- should render page header section with correct styling
- should render Sparkles icon in page header
- should render main content container
- Accessibility
- should have proper semantic HTML structure
- should have descriptive link text
- should maintain focus management during state transitions
- Page Rendering
File: frontend/app/admin/settings/tests/page.test.tsx
- AdminSettingsPage
- with admin user authenticated
- Page Rendering
- should render settings page header
- should render back to admin panel link
- should render settings sidebar with all sections
- should render General section by default
- should render action buttons
- should render Phase 1 notice
- should include Header component
- Section Navigation
- should switch to Branding section when clicked
- should switch to Courses section when clicked
- should switch to AI Generation section when clicked
- should switch to Users & Access section when clicked
- should switch to Email section when clicked
- should switch to Payments section when clicked
- should switch to Analytics section when clicked
- should preserve section selection when navigating between sections
- Settings State Management
- should disable save button when no changes are made
- should enable save button when changes are made
- should show unsaved changes warning when changes are made
- should not show unsaved changes warning initially
- should show discard changes button when changes are made
- Save Functionality
- should save settings when save button is clicked
- should disable save button while saving
- should clear unsaved changes warning after save
- should clear success message after 3 seconds
- Reset Functionality
- should show confirmation dialog when reset is clicked
- should reset settings when confirmed
- should not reset settings when cancelled
- Discard Changes Functionality
- should show confirmation when discard is clicked
- should revert changes when confirmed
- should hide discard button after discarding
- Page Rendering
- with non-admin user
- should redirect non-admin users to dashboard
- should not render settings page for non-admin users
- with unauthenticated user
- should redirect unauthenticated users to signin
- should not render settings page for unauthenticated users
- loading state
- should show loading state while checking authentication
- with admin user authenticated
File: frontend/app/auth/callback/tests/page.test.tsx
- CallbackPage
- Loading State
- should show loading state initially
- OAuth Error Responses
- should handle OAuth error with description
- should handle OAuth error without description
- Missing Parameters
- should handle missing authorization code
- should handle missing state parameter
- Successful OAuth Flow
- should process callback and redirect to dashboard on success
- should call handleOAuthCallback with correct parameters
- Error Handling
- should handle token exchange errors
- should handle CSRF state validation errors
- should handle generic errors
- UI Elements
- should render error state with action buttons
- should render Momentum branding
- should render contact support link
- AuthContext Integration
- should refresh user context after successful authentication
- should not refresh user context on error
- Loading State
File: frontend/app/auth/signin/tests/page.test.tsx
- SignInPage
- should render sign in form
- should render navigation links
- should handle form input changes
- should call signIn with correct credentials on submit
- should display error message on sign in failure
- should disable inputs and show loading state during sign in
- should clear error when form is resubmitted
- should have proper accessibility attributes
- should render remember me checkbox
- should display stats and branding on desktop
File: frontend/app/auth/signup/tests/page.test.tsx
- SignUpPage
- should render sign up form
- should render navigation links
- should handle form input changes
- should validate password match
- should validate password length
- should call signUp with correct data on valid submission
- should display error message on sign up failure
- should disable inputs and show loading state during sign up
- should clear error when form is resubmitted
- should have proper accessibility attributes
- should display password requirements hint
- should display terms and privacy policy links
- should display benefits list on desktop
File: frontend/app/courses/[id]/tests/CourseDetailClient.test.tsx
- CourseDetailClient
- should render the component without crashing
- should display overview tab by default
- should switch to curriculum tab when clicked
- should switch back to overview tab when clicked
- should display all
- should display curriculum with correct week structure
- should show lesson titles in curriculum
- should indicate which lessons are available vs locked
- should have proper tab styling based on active state
- should display student count in call to action
- should render requirements section
- should render
File: frontend/app/courses/[id]/tests/CourseDetailPageClient.test.tsx
- CourseDetailPageClient
- Loading State
- should display loading spinner while fetching course data
- should show loading state with proper styling
- Error Handling
- should display error message when API request fails
- should display default error message for non-Error objects
- should show back to courses button on error
- should handle lessons API failure gracefully
- should display error when course not found in mock data
- UUID-based Course (API)
- should successfully load a UUID-based course from API
- should call API with correct parameters for UUID course
- should convert API course data to UI format correctly
- should create placeholder curriculum when no lessons exist
- should group lessons into weekly curriculum correctly
- Integer-based Course (Mock Data)
- should successfully load an integer-based course from mock data
- should not call API for integer-based course IDs
- should display mock course details correctly
- should render mock instructor information
- Course Details Rendering
- should render course header with correct information
- should render back to courses navigation link
- should render Momentum logo and brand
- should display course duration and lessons count
- should render course preview card with play button
- should render CourseEnrollSection component
- should render CourseDetailClient with correct props
- should display certificate availability badge
- should display default instructor for API courses
- Edge Cases
- should handle course with no thumbnail
- should handle very long course titles
- should handle 7-day course duration
- should handle 21-day course duration
- should handle unordered lessons by sorting them
- should identify UUID correctly with different formats
- should not identify non-UUID strings as UUIDs
- should handle empty lessons array gracefully
- Concurrent API Calls
- should fetch course and lessons in parallel
- Component Cleanup
- should not update state after unmount
- Loading State
File: frontend/app/courses/[id]/lessons/[lessonId]/tests/LessonDetailClient.test.tsx
- LessonDetailClient
- should render the component without crashing
- should display lesson header information
- should render all action items
- should toggle action item completion when clicked
- should update progress bar when action items are completed
- should mark lesson as complete when button is clicked
- should disable complete button after lesson is marked complete
- should display all key takeaways
- should display all resources
- should show next lesson button when next lesson exists
- should not show previous lesson button when no previous lesson exists
- should show both navigation buttons for middle lessons
- should render lesson content
- should display video player
- should strike through completed action items
- should display action items section title
- should display key takeaways section title
- should display resources section title
File: frontend/app/profile/tests/page.test.tsx
- ProfilePage
- renders loading state initially
- fetches statistics and badge progress on mount
- renders profile header
- renders tabs for earned and progress badges
File: frontend/components/admin/tests/CourseForm.test.tsx
- CourseForm Component
- Rendering - Create Mode
- should render form in create mode
- should not show status field in create mode
- should show
- should have empty initial values in create mode
- should have 7 days selected by default
- Rendering - Edit Mode
- should render form in edit mode with course data
- should show status field in edit mode
- should show
- should pre-select correct duration in edit mode
- Form Inputs
- should update title input
- should update description input
- should update category select
- should update price input
- should update thumbnail URL input
- should update status select in edit mode
- should show character count for description
- Duration Selection
- should select 7 days duration
- should select 14 days duration
- should select 21 days duration
- should update duration when changing selection
- Category Options
- should render all category options
- should show placeholder option
- Form Submission
- should call onSubmit with correct data when form is valid
- should show loading state during submission
- should disable submit button during submission
- should disable cancel button during submission
- should handle submission error and display error message
- should handle non-Error exceptions
- should clear error when submitting again
- Cancel Button
- should call onCancel when cancel button is clicked
- should not call onSubmit when cancel is clicked
- Validation
- should have required attribute on title input
- should have required attribute on description input
- should have required attribute on category select
- should have required attribute on price input
- should have maxLength on title input
- should have maxLength on description textarea
- should have min=
- should have step=
- Status Options in Edit Mode
- should render all status options in edit mode
- Styling and UI Elements
- should show red asterisk for required fields
- should show error alert icon when error is present
- should show loading spinner when submitting
- Edge Cases
- should handle form submission with thumbnail URL
- should handle form submission with all fields filled
- should handle very long description
- should handle decimal prices correctly
- Bug Fix: Category Handling from API
- should fetch categories from API on mount
- should display fetched categories in dropdown
- should pre-select category when editing course with category_id
- should fallback to default categories when API fails
- should use fallback categories when API returns empty array
- Bug Fix: Learning Objectives (What You Will Learn)
- should display learning objectives when course has metadata.whatYouWillLearn
- should add a new learning objective
- should not add empty learning objective (whitespace only)
- should remove a learning objective
- should display empty state when no learning objectives exist
- Bug Fix: Requirements
- should display requirements when course has metadata.requirements
- should add a new requirement
- should not add empty requirement (whitespace only)
- should remove a requirement
- should display empty state when no requirements exist
- Bug Fix: Form Submission with Metadata
- should include metadata with learning objectives and requirements in submission
- should submit with updated learning objectives after adding new one
- should submit with updated requirements after adding new one
- should preserve existing metadata fields when submitting
- should submit with empty arrays when no objectives or requirements
- Rendering - Create Mode
File: frontend/components/admin/tests/LessonForm.test.tsx
- LessonForm Component
- Rendering - Create Mode
- should render form in create mode
- should show course selection in create mode
- should show
- should have one empty action item by default
- should have default values in create mode
- Rendering - Edit Mode
- should render form in edit mode with lesson data
- should not show course selection in edit mode
- should show
- should pre-populate action items in edit mode
- should populate content in RichTextEditor in edit mode
- Form Inputs
- should update day number input
- should update order index input
- should update title input
- should update video URL input
- should update course selection
- should update content via RichTextEditor
- Action Items Management
- should add new action item when Add Item is clicked
- should update action item value
- should remove action item when X button is clicked
- should not show remove button when only one action item exists
- should handle multiple action items
- Form Submission
- should call onSubmit with correct data when form is valid
- should filter out empty action items on submit
- should show loading state during submission
- should disable submit button during submission
- should disable cancel button during submission
- should handle submission error and display error message
- should handle non-Error exceptions
- should clear error when submitting again
- Cancel Button
- should call onCancel when cancel button is clicked
- should not call onSubmit when cancel is clicked
- Validation
- should have required attribute on course select in create mode
- should have required attribute on day number input
- should have required attribute on order index input
- should have required attribute on title input
- should have min=
- should have min=
- should have maxLength on title input
- Edge Cases
- should handle empty courses array with warning message
- should handle lesson with no action items
- should handle lesson with no video URL
- should handle form submission with video URL
- should handle submission with all action items empty
- UI Elements
- should show Add Item button
- should show error alert when error occurs
- AI Generation Prompt Field
- should render AI generation prompt textarea in create mode
- should render AI generation prompt textarea in edit mode
- should have empty value by default in create mode
- should populate existing generation_prompt in edit mode
- should update generation_prompt when typing
- should include generation_prompt in form submission
- should include empty generation_prompt if not provided
- should have correct placeholder text
- should have 4 rows for the textarea
- Generate Lesson Button
- should not show Generate Lesson button in create mode
- should show Generate Lesson button in edit mode
- should not show Generate Lesson button when lesson has no id
- should call regenerateLesson API when Generate Lesson button is clicked
- should pass generation_prompt to API when provided
- should show loading state while generating
- should disable Generate button during generation
- should disable submit button during generation
- should disable cancel button during generation
- should show success message after successful generation
- should update generation_prompt field after successful generation
- should show error message if generation fails
- should handle non-Error exceptions during generation
- should clear error when generating again after failure
- should clear success message when starting new generation
- should have Wand2 icon in Generate Lesson button
- should have correct button styling
- Rendering - Create Mode
File: frontend/components/admin/tests/RichTextEditor.test.tsx
- RichTextEditor Component
- Rendering
- should render the editor component
- should render with default placeholder
- should render with custom placeholder
- should render in non-readonly mode by default
- should render in readonly mode when specified
- should render with snow theme
- should render toolbar
- Value Management
- should display the initial value
- should update when value prop changes
- should handle empty value
- should handle HTML content
- Change Handling
- should call onChange when content is typed
- should call onChange with updated value
- should not call onChange in readonly mode
- Toolbar Configuration
- should configure toolbar with header options
- should configure toolbar with text formatting options
- should configure toolbar with list options
- should configure toolbar with blockquote and code-block
- should configure toolbar with color options
- should configure toolbar with link option
- should configure toolbar with clean option
- Format Configuration
- should configure supported formats
- should have exactly 12 supported formats
- Styling
- should apply rich-text-editor wrapper class
- should apply styling classes to ReactQuill
- Dynamic Import Behavior
- should render without SSR (mocked behavior)
- Edge Cases
- should handle very long content
- should handle special characters in content
- should handle content with line breaks
- should handle rapid onChange calls
- should handle switching between readonly states
- should handle null or undefined onChange gracefully
- should handle multiple editor instances
- Placeholder Behavior
- should show placeholder when value is empty
- should not show placeholder when value is present
- Rendering
File: frontend/components/admin/ai-generation/tests/CourseGenerationForm.test.tsx
- CourseGenerationForm
- Fallback Categories
- should use category slugs as IDs in fallback categories
- should submit form with category slug when API fails
- should display correct fallback category names
- should prefer API categories over fallback when available
- Form Rendering
- should render all form sections
- should render info card explaining AI generation process
- should render course title input with required marker
- should render category select with all options
- should render all duration options
- should render target audience and difficulty fields
- should render tone selection buttons
- should render learning objectives section
- should render generation toggle switches
- should render submit button
- Form Input Interactions
- should update title input value
- should update category selection
- should update target audience input
- should update difficulty level selection
- should update reference materials textarea
- Duration Selection
- should select 7 days duration by default
- should change duration to 7 days when clicked
- should change duration to 21 days when clicked
- should update visual state when switching durations
- Learning Objectives
- should add learning objective when Add button is clicked
- should add objective when Enter key is pressed
- should remove learning objective when X button is clicked
- should allow up to 6 learning objectives
- should disable add button when 6 objectives are reached
- should not add empty objectives
- should trim whitespace from objectives
- Tone Selection
- should select friendly tone by default
- should change tone to professional when clicked
- should change tone to academic when clicked
- Toggle Switches
- should toggle async mode when clicked
- should toggle video generation when clicked
- should have proper ARIA attributes for toggle switches
- should display correct text for async mode states
- Form Submission
- should submit form with correct data when all required fields are filled
- should call onGenerationStart with jobId on successful submission
- should show loading state during submission
- should disable submit button when title is empty
- should disable submit button when category is empty
- should include learning objectives in submission when provided
- should include reference materials in submission when provided
- Error Handling
- should display error message when API call fails
- should display generic error when API returns no error message
- should handle network errors
- should clear error when resubmitting
- Accessibility
- should have proper ARIA labels for required fields
- should have descriptive placeholders
- should have proper button labels
- should have accessible remove buttons for objectives
- Text Contrast and Styling
- should have proper text contrast classes on course title input
- should have proper text contrast classes on category select
- should have proper text contrast classes on target audience input
- should have proper text contrast classes on difficulty level select
- should have proper text contrast classes on learning objectives input
- should have proper text contrast classes on reference materials textarea
- should maintain text contrast classes after user input on title field
- should maintain text contrast classes after selection on category field
- should maintain text contrast classes after user input on target audience field
- should maintain text contrast classes after selection on difficulty field
- should ensure all form inputs have white background for consistent contrast
- should ensure all text inputs have dark text color for readability
- should ensure all select elements have dark text color for readability
- should ensure placeholder text has adequate contrast
- Fallback Categories
File: frontend/components/admin/ai-generation/tests/GeneratedCoursePreview.test.tsx
- GeneratedCoursePreview
- Metrics Cards Rendering
- should render all metric cards
- should display quality score as percentage
- should display formatted tokens used
- should display formatted cost with 4 decimal places
- Course Data Display
- should display success header
- should display course title
- should display course duration
- should display course status badge
- should display instructor information
- should show default instructor when not provided
- Tab Switching
- should render both tabs
- should show overview tab by default
- should switch to lessons tab when clicked
- should display what you will learn section
- should display requirements section
- should display lessons with day numbers
- should show empty state when no lessons
- Regenerate Lesson Functionality
- should show regenerate button for each lesson
- should call API when regenerate button is clicked
- should show loading state while regenerating
- should update lesson data after successful regeneration
- Action Buttons
- should render all action buttons
- should call onStartOver when Generate Another Course is clicked
- should have correct link for Preview Course
- should have correct link for Edit & Publish
- should render edit and regenerate buttons for each lesson
- Loading and Error States
- should show loading spinner while fetching course
- should show error message when course fetch fails
- should show start over button when course fetch fails
- should handle network errors when fetching course
- Accessibility
- should have proper ARIA labels for regenerate buttons
- should have accessible tab navigation
- should have accessible action buttons
- Metrics Cards Rendering
File: frontend/components/admin/ai-generation/tests/GenerationProgress.test.tsx
- GenerationProgress
- Component Rendering
- should render progress component
- should show progress bar
- should display current step description
- should render step timeline
- Progress Display and Animation
- should show correct progress percentage
- should update progress bar width based on percentage
- should show spinning animation for current status
- should not show spinning animation when completed
- Step Timeline Rendering
- should mark completed steps with check icon
- should highlight current step
- should show pending steps in gray
- Completion State
- should call onComplete when status is COMPLETED
- should display completion message
- should stop polling after completion
- Error State Rendering
- should display error message when status is FAILED
- should show error icon when failed
- should render Try Again button on error
- should handle fetch errors gracefully
- should stop polling after failure
- Polling Behavior
- should poll status API every 2 seconds
- should call correct API endpoint with jobId
- should clean up interval on unmount
- Metrics Display
- should show tokens used when available
- should show estimated cost when available
- should not show metrics section when tokens are 0
- Accessibility
- should have proper semantic structure
- should have accessible error button
- Component Rendering
File: frontend/components/admin/ai-generation/sections/tests/AudienceSection.test.tsx
- AudienceSection Component
- Rendering
- should render section header with icon
- should render target audience input field
- should render difficulty level select field
- should render all difficulty level options
- should render all tone options
- should render course tone label
- Target Audience Input
- should display current target audience value
- should display empty value when target audience is not set
- should call setFormData when target audience is changed
- should update target audience value on change
- should handle long target audience text
- Difficulty Level Selection
- should display current difficulty level (beginner by default)
- should display intermediate difficulty when selected
- should display advanced difficulty when selected
- should call setFormData when difficulty level is changed
- should update difficulty level on change
- Tone Selection
- should highlight friendly tone by default
- should highlight professional tone when selected
- should highlight academic tone when selected
- should not highlight unselected tone buttons
- should call setFormData when tone button is clicked
- should update tone to professional when clicked
- should update tone to academic when clicked
- should have proper button type for tone buttons
- Layout
- should use grid layout for target audience and difficulty
- should render tone section spanning full width on medium screens
- Accessibility
- should have accessible labels for all form fields
- should capitalize tone button text
- Edge Cases
- should handle switching between all tones
- should handle switching between all difficulty levels
- should handle empty target audience gracefully
- Height Consistency Fix
- should have min-h-12 class on target audience input for consistent minimum height
- should have min-h-12 class on difficulty level select for consistent minimum height
- should have consistent minimum height (48px) between input and select elements
- should verify input element has proper styling classes including min-h-12
- should verify select element has proper styling classes including min-h-12
- Rendering
File: frontend/components/admin/ai-generation/sections/tests/BasicInfoSection.test.tsx
- BasicInfoSection Component
- Rendering
- should render section header with icon
- should render title input field
- should render category select field
- should render all duration options
- should mark title as required
- should mark category as required
- should display required asterisk for title
- should display required asterisk for category
- Title Input
- should display current title value
- should call setFormData when title is changed
- should update title value on change
- Category Selection
- should display all categories as options
- should display placeholder option when not loading
- should display loading text when loading categories
- should disable select when loading categories
- should display current category value
- should call setFormData when category is changed
- should update category value on change
- Duration Selection
- should highlight selected duration (14 days by default)
- should highlight 7 days when selected
- should highlight 21 days when selected
- should call setFormData when duration button is clicked
- should update duration to 7 days when clicked
- should update duration to 21 days when clicked
- should not highlight unselected duration buttons
- Accessibility
- should have accessible labels for all form fields
- should have proper button types for duration buttons
- Edge Cases
- should handle empty categories array
- should handle long category names
- should handle long course titles
- Height Consistency Fix
- should have min-h-12 class on course title input for consistent minimum height
- should have min-h-12 class on category select for consistent minimum height
- should have consistent minimum height (48px) between input and select elements
- should verify input element has proper styling classes including min-h-12
- should verify select element has proper styling classes including min-h-12
- Rendering
File: frontend/components/admin/ai-generation/sections/tests/GenerationOptionsSection.test.tsx
- GenerationOptionsSection Component
- Rendering
- should render section header with icon
- should render generation mode toggle
- should render video generation toggle
- should render video generation description
- should render both toggle switches
- Generation Mode Toggle
- should display
- should display
- should have inactive styling when isAsync is false
- should have active styling when isAsync is true
- should call setFormData when toggle is clicked
- should toggle isAsync value on click
- should toggle from true to false
- should have aria-checked attribute matching isAsync state
- should have aria-checked=
- should have type=
- Video Generation Toggle
- should have active styling when generateVideo is true (default)
- should have inactive styling when generateVideo is false
- should call setFormData when toggle is clicked
- should toggle generateVideo value on click
- should toggle from false to true
- should have aria-checked attribute matching generateVideo state
- should have aria-checked=
- should have type=
- Toggle Switch Appearance
- should position toggle knob to the left when inactive
- should position toggle knob to the right when active
- should position video toggle knob to the right when active (default)
- should position video toggle knob to the left when inactive
- Accessibility
- should have role=
- should have accessible labels for toggles
- should have proper aria-checked attributes
- Interactive Behavior
- should handle rapid clicks on async toggle
- should handle rapid clicks on video toggle
- should handle clicking both toggles sequentially
- Edge Cases
- should handle both toggles being true
- should handle both toggles being false
- should handle mixed toggle states
- Layout
- should render options in a vertical stack
- should render each option in a card-like container
- Rendering
File: frontend/components/admin/ai-generation/sections/tests/LearningObjectivesSection.test.tsx
- LearningObjectivesSection Component
- Rendering
- should render section header with icon
- should render input field for adding objectives
- should render add button
- should render helper text about max objectives
- should not render objectives list when empty
- should render objectives list when objectives exist
- Objective Input
- should display current objective input value
- should call setObjectiveInput when input changes
- should call addObjective when Enter key is pressed
- should prevent default when Enter key is pressed
- Add Button
- should call addObjective when add button is clicked
- should be enabled when less than 6 objectives
- should be disabled when 6 objectives are reached
- should have proper button type
- Objectives List
- should display all objectives
- should render remove button for each objective
- should call removeObjective with correct index when remove button is clicked
- should have accessible labels for remove buttons
- should render objectives in list items
- Maximum Limit
- should display all 6 objectives when at max
- should disable add button at max limit
- should have disabled styles on add button at max limit
- Accessibility
- should have accessible input field
- should have type=
- Edge Cases
- should handle empty objectives array
- should handle single objective
- should handle long objective text
- should handle objectives with special characters
- should handle rapid clicks on remove button
- should handle rapid clicks on add button
- Rendering
File: frontend/components/admin/ai-generation/sections/tests/ReferenceMaterialsSection.test.tsx
- ReferenceMaterialsSection Component
- Rendering
- should render section header with icon
- should render text references textarea
- should render PDF upload section
- should render helper text for text references
- should render helper text for PDF upload
- Text References Textarea
- should display current reference materials value
- should display empty value when no materials
- should call onReferenceMaterialsChange when textarea changes
- should have 4 rows
- should have placeholder text
- should handle multiline input
- PDF Upload - No File
- should display upload area when no file is uploaded
- should display upload icon
- should display file size limit
- should have hidden file input
- should accept only PDF files
- should call onPdfUpload when file is selected
- PDF Upload - With File
- should display file info when file is uploaded
- should display file size
- should display remove button when file is uploaded
- should call onPdfRemove when remove button is clicked
- should not display upload area when file is uploaded
- should have file icon in uploaded file display
- should have proper button type for remove button
- File Size Display
- should display file size in KB for small files
- should display file size in KB for large files
- should format file size to one decimal place
- Accessibility
- should have accessible labels for all inputs
- should have aria-label for remove button
- Edge Cases
- should handle long file names
- should handle file names with special characters
- should handle very small file sizes
- should handle very long reference materials text
- should handle reference materials with URLs
- Rendering
File: frontend/components/admin/analytics/tests/DateRangePicker.test.tsx
- DateRangePicker Component
- Rendering - Range Options
- should render all predefined range options
- should render exactly 5 range buttons
- should highlight the selected range
- should not highlight non-selected ranges
- Range Selection
- should call onChange when 7d range is clicked
- should call onChange when 30d range is clicked
- should call onChange when 90d range is clicked
- should call onChange when 1y range is clicked
- should call onChange when custom range is clicked
- should allow changing between different ranges
- Custom Date Range Inputs
- should show custom date inputs when custom range is selected
- should not show custom date inputs when other ranges are selected
- should display customStart date in start input
- should display customEnd date in end input
- should call onChange with custom start date when start input changes
- should call onChange with custom end date when end input changes
- should show
- should render calendar icons for date inputs
- Styling and Layout
- should render with flex layout
- should apply active styling to selected range
- should apply inactive styling to non-selected ranges
- should have hover effect on inactive buttons
- should have rounded corners on buttons
- should have consistent padding on buttons
- should render date inputs with correct styling
- should show focus styling on date inputs
- Edge Cases
- should handle selecting the same range twice
- should handle undefined custom dates
- should handle invalid date formats gracefully
- should handle switching from custom to predefined range
- should handle switching from predefined to custom range
- should maintain date values when switching away and back to custom
- Date Input Behavior
- should have type=
- should format date values correctly (ISO format)
- should have calendar icon positioned correctly
- Accessibility
- should have proper button role for all range options
- should have descriptive button labels
- should have proper input type for date fields
- Rendering - Range Options
File: frontend/components/admin/analytics/tests/KPICard.test.tsx
- KPICard Component
- Rendering - Basic Props
- should render with minimum required props
- should render the provided icon
- should render with string value
- should render with numeric value
- Value Formatting
- should format number values correctly (small numbers)
- should format number values correctly (thousands)
- should format number values correctly (millions)
- should format currency values correctly (small amounts)
- should format currency values correctly (thousands)
- should format currency values correctly (millions)
- should format percent values correctly
- should format duration values correctly (minutes only)
- should format duration values correctly (hours and minutes)
- should format duration values correctly (hours only)
- Trend Indicators
- should display upward trend with correct styling
- should display downward trend with correct styling
- should display neutral trend with correct styling
- should display positive change with plus sign
- should display negative change without extra minus sign
- should not display trend when change is undefined
- Change Label
- should display default change label
- should display custom change label
- should not display change label when change is undefined
- Loading State
- should show loading skeleton when loading is true
- should show value when loading is false
- should show title even when loading
- Styling and UI Elements
- should have correct card styling classes
- should have hover transition effect
- should render icon in gradient container
- should apply correct text styles to title
- should apply correct text styles to value
- Edge Cases
- should handle zero value
- should handle zero change
- should handle very large numbers
- should handle decimal change values
- should handle empty string value
- Accessibility
- should render semantic HTML structure
- should have readable text contrast
- Rendering - Basic Props
File: frontend/components/admin/analytics/tests/KPICardGrid.test.tsx
- KPICardGrid Component
- Rendering - With Data
- should render all 5 KPI cards
- should display correct data for Total Users card
- should display correct data for Active Users card
- should display correct data for Course Completions card
- should display correct data for Avg Time per User card
- should display correct data for Revenue card
- Rendering - Without Data
- should render with null data
- should display zero values when data is null
- Loading State
- should pass loading prop to all KPI cards when loading is true
- should not show loading when loading is false
- should default to not loading
- Trend Calculation
- should show upward trend when users_change is positive
- should show downward trend when users_change is negative
- should handle missing comparison data gracefully
- should show upward trend for positive completions_change
- should show upward trend for positive revenue_change
- Grid Layout
- should render grid container with correct classes
- should render exactly 5 cards in the grid
- Edge Cases
- should handle zero values in all metrics
- should handle very large numbers
- should handle partial analytics data
- should handle undefined comparison changes
- Data Integrity
- should correctly map overview data to KPI cards
- should correctly map comparison data to trend changes
- Rendering - With Data
File: frontend/components/admin/course-form/tests/EditableList.test.tsx
- EditableList
- Rendering
- should render label correctly
- should render empty state when no items
- should render items with their values and IDs as keys
- should render correct variant styling for success variant
- should render correct variant styling for neutral variant
- should show item icon if provided
- should not show item icon if not provided
- Input Field
- should render input field with placeholder
- should render input field with default maxLength
- should render input field with custom maxLength
- should display current newItemValue
- should call onNewItemChange when input value changes
- should have correct styling classes
- Add Button
- should render add button with correct text
- should call onAdd when add button is clicked
- should call onAdd multiple times on multiple clicks
- Enter Key Behavior
- should call onAdd when Enter key is pressed in input
- should prevent default behavior when Enter key is pressed
- should not call onAdd when other keys are pressed
- Remove Button
- should render remove button for each item
- should call onRemove with correct ID when remove button is clicked
- should call onRemove with correct IDs for different items
- should have correct type attribute
- should have correct styling classes
- Accessibility
- should have aria-label on remove buttons
- should use custom removeAriaLabel for each remove button
- should have semantic HTML structure
- Edge Cases
- should handle empty items array
- should handle single item
- should handle items with very long values
- should handle items with special characters
- should handle empty string newItemValue
- should handle rapid successive add button clicks
- should handle rapid successive remove button clicks on different items
- Integration Scenarios
- should handle complete add workflow
- should handle complete add workflow with Enter key
- should handle adding and removing items in sequence
- should maintain focus on input after adding item
- Visual Regression Prevention
- should maintain consistent DOM structure with items
- should apply correct spacing classes
- Rendering
File: frontend/components/admin/lesson-form/tests/ActionItemsList.test.tsx
- ActionItemsList Component
- Rendering
- should render label and add button
- should render all action items with their values
- should render correct number of input fields
- should render input fields with correct placeholders
- should render with empty values
- should use stable keys (item.id) for rendering
- Remove Button Visibility
- should NOT show remove button when there is only 1 item
- should show remove buttons when there are 2 items
- should show remove buttons when there are multiple items
- User Interactions
- Input Value Changes
- should call onItemChange when input value changes
- should call onItemChange with correct item.id for second item
- should call onItemChange with correct item.id and value
- should handle typing special characters
- should handle clearing input value
- Add Item Button
- should call onAdd when
- should call onAdd multiple times when clicked multiple times
- Remove Item Button
- should call onRemove when remove button is clicked
- should call onRemove with correct item.id for first item
- should call onRemove with correct item.id for second item
- should call onRemove with correct item.id for third item
- Input Value Changes
- Accessibility
- should have ARIA label on Add Item button
- should have ARIA labels on all input fields
- should have ARIA labels on remove buttons
- should have proper role=
- should have role=
- should have aria-labelledby connecting list to label
- should have aria-hidden on icon elements
- Edge Cases
- should render with empty items array
- should handle items with very long values
- should handle items with special characters in values
- should handle items with duplicate values but different IDs
- Rendering
File: frontend/components/admin/lesson-form/tests/LessonBasicFields.test.tsx
- LessonBasicFields Component
- Course Selection Field
- Visibility Based on isEditing
- should show course dropdown when NOT editing (isEditing=false)
- should hide course dropdown when editing (isEditing=true)
- should show course dropdown in create mode
- should not show course dropdown in edit mode
- With Available Courses
- should render course select with all course options
- should render default
- should render all course titles as options
- should set selected course value correctly
- should have required attribute on course select
- should show asterisk for required field
- With Empty Courses Array
- should show warning message when courses array is empty
- should display helpful message about creating course first
- should NOT show course select when courses array is empty
- should show warning with proper styling
- Visibility Based on isEditing
- Day Number Field
- should render day number input
- should display correct day value
- should have min value of 1
- should have max value of 21
- should be required
- should be type number
- should show asterisk for required field
- Order Index Field
- should render order index input
- should display correct order index value
- should have min value of 0
- should be required
- should be type number
- should show asterisk for required field
- Title Field
- should render title input
- should display correct title value
- should have maxLength of 500
- should be required
- should be type text
- should have placeholder text
- should show asterisk for required field
- Video URL Field
- should render video URL input
- should display correct video URL value
- should be type url
- should NOT be required (optional field)
- should have placeholder text
- should NOT show asterisk (optional field)
- should handle empty video URL
- User Interactions - onChange Handler
- Course Selection
- should call onChange when course is selected
- should call onChange with different course selection
- Day Number Input
- should call onChange when day number changes
- should call onChange with different day values
- Order Index Input
- should call onChange when order index changes
- should call onChange with order index 0
- Title Input
- should call onChange when title changes
- should call onChange multiple times as user types
- should handle clearing title
- Video URL Input
- should call onChange when video URL changes
- should handle clearing video URL
- onChange Called with Correct Event Properties
- should call onChange with proper event structure
- Course Selection
- Edge Cases
- should handle day value at minimum boundary (1)
- should handle day value at maximum boundary (21)
- should handle order index at minimum boundary (0)
- should handle very long title (up to 500 chars)
- should handle special characters in title
- should handle single course in courses array
- should handle very long course title
- Form Field Structure
- should render all required fields in create mode
- should render all fields except course in edit mode
- should have proper input IDs matching label htmlFor
- should have proper input names for form submission
- Height Consistency Fix
- should have min-h-12 class on course select for consistent minimum height
- should have min-h-12 class on day number input for consistent minimum height
- should have min-h-12 class on order index input for consistent minimum height
- should have min-h-12 class on lesson title input for consistent minimum height
- should have min-h-12 class on video URL input for consistent minimum height
- should have consistent minimum height (48px) between all input and select elements
- should verify select element has proper styling classes including min-h-12
- should verify input elements have proper styling classes including min-h-12
- Course Selection Field
File: frontend/components/admin/lesson-form/tests/LessonContentEditor.test.tsx
- LessonContentEditor Component
- AI Generation Prompt Section
- Rendering
- should render AI generation prompt label
- should render AI prompt textarea
- should display current prompt value
- should show empty textarea when no prompt provided
- should have 4 rows in textarea
- should have placeholder text
- should have proper name attribute
- should have proper id attribute
- should show optional field note
- should NOT be required (optional field)
- User Interactions
- should call onPromptChange when textarea value changes
- should call onPromptChange with correct event
- should call onPromptChange multiple times as user types
- should handle clearing prompt text
- should handle typing special characters
- should handle multi-line prompt text
- Rendering
- Rich Text Editor Section
- Rendering
- should render lesson content label
- should show required asterisk on content label
- should render rich text editor
- should render rich text editor with content
- should render rich text editor with empty content
- should pass placeholder to rich text editor
- User Interactions
- should call onContentChange when content changes
- should call onContentChange with updated content
- should call onContentChange multiple times as user types
- should handle HTML content in editor
- should handle clearing content
- Rendering
- Component Integration
- should render both prompt and content sections together
- should handle updates to both sections independently
- should maintain separate values for prompt and content
- Edge Cases
- should handle very long prompt text
- should handle very long content
- should handle prompt with newlines
- should handle content with complex HTML
- should handle prompt with special characters
- should handle empty strings for both fields
- Styling and Layout
- should apply proper CSS classes to prompt container
- should apply proper CSS classes to content container
- should have proper styling classes on prompt textarea
- should have proper label styling
- AI Generation Prompt Section
File: frontend/components/admin/settings/fields/tests/ColorField.test.tsx
- ColorField
- Basic Rendering
- should render with label
- should render with description
- should render color picker input
- should render text input for hex value
- should render default preset colors
- Color Picker Interactions
- should call onChange when color picker value changes
- should display current color in color picker
- should fallback to black when invalid hex is provided
- Text Input Interactions
- should call onChange when text input value changes
- should add # prefix if missing when typing
- should allow # to be typed
- should have monospace font for hex value
- should show placeholder text
- Preset Colors
- should render default preset colors
- should render custom preset colors
- should call onChange when preset is clicked
- should highlight selected preset color
- should not highlight non-selected preset colors
- should apply correct background color to presets
- should not render presets when empty array is provided
- should show title attribute on preset buttons
- Disabled State
- should be enabled by default
- should disable all inputs when disabled
- should disable preset buttons when disabled
- should not call onChange when preset is clicked while disabled
- should apply disabled styling to color picker
- should apply disabled styling to text input
- should apply disabled styling to preset buttons
- Error Handling
- should show error message when error prop is provided
- should apply error styling to text input
- should apply normal styling when no error
- should not show error message when error prop is not provided
- Hex Validation
- should accept valid 6-digit hex colors
- should accept valid 3-digit hex colors
- should handle lowercase hex values
- should handle uppercase hex values
- Accessibility
- should have proper label
- should have aria-label on preset buttons
- should be keyboard accessible for preset buttons
- Styling
- should apply proper layout classes
- should have rounded corners on color picker
- should have focus ring on text input
- should wrap preset buttons
- Basic Rendering
File: frontend/components/admin/settings/fields/tests/FileUploadField.test.tsx
- FileUploadField
- Basic Rendering
- should render with label
- should render with description
- should render without description when not provided
- should render mode toggle buttons
- should default to URL mode
- should render URL input in URL mode
- Mode Switching
- should switch to upload mode when upload button is clicked
- should switch back to URL mode when URL button is clicked
- should show file upload UI in upload mode
- should show URL input in URL mode
- URL Input Mode
- should call onChange when URL is entered
- should update value when typing URL
- should show clear button when value exists
- should not show clear button when value is empty
- should call onChange with empty string when clear is clicked
- File Upload Mode
- should accept file input
- should accept image files by default
- should accept custom file types
- should handle file selection with FileReader
- should handle file upload without errors
- should show clear button in upload mode when value exists
- Image Preview
- should show preview when value is set
- should not show preview when value is empty
- should apply small preview size
- should apply medium preview size by default
- should apply large preview size
- should have error handling for image load failure
- should have load handler for successful image loads
- should clear preview error when clear button is clicked
- should clear preview error when URL changes
- Disabled State
- should be enabled by default
- should disable URL input when disabled
- should disable mode toggle buttons when disabled
- should disable file input when disabled
- should disable clear button when disabled
- should not call onChange when disabled
- should apply disabled styling
- Error Handling
- should show error message when error prop is provided
- should apply error styling when error is present
- should apply normal styling when no error
- should not show error message when error prop is not provided
- should handle FileReader error
- Accessibility
- should have proper label
- should have descriptive button labels
- should have clear button with title attribute
- should have preview with alt text
- Styling
- should apply base styling classes to input
- should have focus styling
- should style active mode button differently
- Basic Rendering
File: frontend/components/admin/settings/fields/tests/NumberField.test.tsx
- NumberField
- Basic Rendering
- should render with label
- should render with description
- should render with initial value
- should render with placeholder
- should show required indicator when required
- should not show required indicator when not required
- User Interactions
- should call onChange when number is entered
- should update value when typing
- should handle decimal values
- should handle negative values when allowed
- should clear value to 0 when input is cleared
- should not call onChange with NaN values
- Min/Max Validation
- should show range info when min and max are set
- should show minimum info when only min is set
- should show maximum info when only max is set
- should not show range info when min and max are not set
- should have min attribute on input
- should have max attribute on input
- Step Attribute
- should use step value of 1 by default
- should use custom step value when provided
- Suffix Display
- should display suffix when provided
- should not display suffix when not provided
- should position suffix on the right side
- should add padding to input when suffix is present
- Disabled State
- should be enabled by default
- should be disabled when disabled prop is true
- should not call onChange when disabled
- should have disabled styling when disabled
- Error Handling
- should show error message when error prop is provided
- should apply error styling when error is present
- should apply normal styling when no error
- should not show error message when error prop is not provided
- Accessibility
- should have proper label association
- should have required attribute when required
- should not have required attribute when not required
- should have spinbutton role
- Styling
- should apply base styling classes
- should have focus styling
- should have white background
- Edge Cases
- should handle zero value
- should handle very large numbers
- should handle very small decimal numbers
- Basic Rendering
File: frontend/components/admin/settings/fields/tests/SelectField.test.tsx
- SelectField
- Basic Rendering
- should render with label
- should render with description
- should render select dropdown
- should show required indicator when required
- should not show required indicator when not required
- Options Rendering
- should render all provided options
- should render placeholder option
- should use default placeholder when not provided
- should have empty value for placeholder option
- should set correct values for options
- should render empty options list correctly
- Value Selection
- should display selected value
- should show placeholder when no value selected
- User Interactions
- should call onChange when option is selected
- should update selection when different option is chosen
- should allow selecting placeholder to clear selection
- Disabled State
- should be enabled by default
- should be disabled when disabled prop is true
- should not call onChange when disabled
- should have disabled styling when disabled
- Error Handling
- should show error message when error prop is provided
- should apply error styling when error is present
- should apply normal styling when no error
- should not show error message when error prop is not provided
- Accessibility
- should have proper label association
- should have required attribute when required
- should not have required attribute when not required
- should be keyboard navigable
- Styling
- should apply base styling classes
- should have focus styling
- should have white background
- should have min-h-12 height class for consistent minimum height with input elements
- Custom Placeholder
- should display custom placeholder text
- should not display custom placeholder when value is selected
- Basic Rendering
File: frontend/components/admin/settings/fields/tests/TextAreaField.test.tsx
- TextAreaField
- Basic Rendering
- should render with label
- should render with description
- should render without description when not provided
- should render with initial value
- should render with placeholder
- should show required indicator when required
- should not show required indicator when not required
- should render as textarea element
- Rows Configuration
- should have 4 rows by default
- should accept custom rows value
- should accept small rows value
- User Interactions
- should call onChange when text is entered
- should update value when typing
- should handle multi-line text input
- should clear value when cleared
- should handle paste operations
- Disabled State
- should be enabled by default
- should be disabled when disabled prop is true
- should not call onChange when disabled
- should have disabled styling when disabled
- should have enabled styling when not disabled
- Max Length Validation
- should show character count when maxLength is set
- should update character count as user types
- should enforce maxLength attribute on textarea
- should not show character count when maxLength is not set
- should show correct count for empty value
- should show correct count near limit
- should show correct count at limit
- Error Handling
- should show error message when error prop is provided
- should apply error styling when error is present
- should apply normal styling when no error
- should not show error message when error prop is not provided
- should show both error message and character count
- Accessibility
- should have proper label association
- should have required attribute when required
- should not have required attribute when not required
- should have placeholder for user guidance
- Styling
- should apply base styling classes
- should have focus styling
- should have transition classes
- should prevent resizing
- should have proper text color classes
- Component Integration
- should work as controlled component
- should handle rapid typing
- should preserve whitespace in value
- Basic Rendering
File: frontend/components/admin/settings/fields/tests/TextField.test.tsx
- TextField
- Basic Rendering
- should render with label
- should render with description
- should render with initial value
- should render with placeholder
- should show required indicator when required
- should not show required indicator when not required
- Input Types
- should render as text input by default
- should render as email input when type is email
- should render as url input when type is url
- User Interactions
- should call onChange when text is entered
- should update value when typing
- should clear value when cleared
- Disabled State
- should be enabled by default
- should be disabled when disabled prop is true
- should not call onChange when disabled
- should have disabled styling when disabled
- Max Length Validation
- should show character count when maxLength is set
- should update character count as user types
- should enforce maxLength attribute on input
- should not show character count when maxLength is not set
- Error Handling
- should show error message when error prop is provided
- should apply error styling when error is present
- should apply normal styling when no error
- should not show error message when error prop is not provided
- Accessibility
- should have proper label association
- should have required attribute when required
- should not have required attribute when not required
- Styling
- should apply base styling classes
- should have focus styling
- Basic Rendering
File: frontend/components/admin/settings/fields/tests/ToggleField.test.tsx
- ToggleField
- Basic Rendering
- should render with label
- should render with description
- should render without description when not provided
- should render toggle switch button
- Toggle State
- should show off state when value is false
- should show on state when value is true
- should position knob on left when off
- should position knob on right when on
- User Interactions
- should call onChange with true when toggled from false
- should call onChange with false when toggled from true
- should toggle multiple times correctly
- Disabled State
- should be enabled by default
- should be disabled when disabled prop is true
- should not call onChange when disabled and clicked
- should apply disabled styling when disabled
- should apply enabled styling when not disabled
- Accessibility
- should have switch role
- should have aria-checked attribute matching value
- should be keyboard accessible
- should support space key press
- Layout and Styling
- should have proper layout structure
- should have gray background
- should have transition classes for smooth animation
- should have proper sizing classes
- Visual States
- should show correct colors when enabled and off
- should show correct colors when enabled and on
- should maintain state color even when disabled
- Basic Rendering
File: frontend/components/admin/user-edit/tests/DemographicsSection.test.tsx
- DemographicsSection Component
- Rendering
- should render section title with icon
- should render gender select field
- should render age group select field
- Gender Selection
- should display empty string as default
- should display selected gender value
- should render all gender options
- should call onChange when gender is changed to male
- should call onChange when gender is changed to female
- should call onChange when gender is changed to non-binary
- should call onChange when gender is changed to prefer-not-to-say
- should call onChange when gender is changed to other
- should call onChange when gender is reset to not specified
- Age Group Selection
- should display empty string as default
- should display selected age group value
- should render all age group options
- should call onChange when age group is changed
- should call onChange for all age groups
- should call onChange when age group is reset to not specified
- Combined Interactions
- should handle both gender and age group changes independently
- should handle interleaved changes
- Styling and Structure
- should render with card structure
- should have gradient header
- should display User icon in header
- should use grid layout for fields
- should have proper spacing between fields
- should style selects consistently
- Accessibility
- should have proper labels for both selects
- should have semantic heading
- should have keyboard navigable elements
- should associate selects with labels
- Props Handling
- should update when gender prop changes
- should update when ageGroup prop changes
- should call different onChange callbacks
- Edge Cases
- should handle all gender values correctly
- should handle all age group values correctly
- should maintain state consistency with external updates
- should not call onChange on initial render
- should handle rapid successive changes
- Rendering
File: frontend/components/admin/user-edit/tests/FormSection.test.tsx
- FormSection Component
- Rendering
- should render section title
- should render children content
- should render icon in header
- should accept different icons
- Styling
- should have card structure with proper classes
- should have gradient header
- should have proper header padding and border
- should have proper content padding
- should have bottom margin
- should apply additional className if provided
- Accessibility
- should have semantic heading
- should render children in accessible order
- Children Handling
- should render multiple children
- should render nested components
- should render form elements
- Rendering
File: frontend/components/admin/user-edit/tests/LearningPreferencesSection.test.tsx
- LearningPreferencesSection Component
- Rendering
- should render section title with icon
- should render learning style select
- should render weekly hours input
- should render interests input
- should render learning objectives textarea
- Learning Style Selection
- should display empty string as default
- should display selected learning style
- should render all learning style options
- should call onChange when learning style is changed
- should handle all learning style values
- should reset to not specified
- Weekly Hours Input
- should display empty weekly hours by default
- should display provided weekly hours value
- should have number input type
- should have min and max attributes
- should have placeholder text
- should call onChange when weekly hours is typed
- should call onChange when weekly hours is cleared
- Interests Input
- should display empty interests by default
- should display provided interests value
- should have placeholder text
- should call onChange when interests is typed
- should call onChange when interests is cleared
- should handle comma-separated interests
- Learning Objectives Textarea
- should display empty learning objectives by default
- should display provided learning objectives value
- should have placeholder text
- should have 3 rows
- should call onChange when learning objectives is typed
- should call onChange when learning objectives is cleared
- should handle multi-line text
- Combined Interactions
- should handle changes to all fields independently
- Styling and Structure
- should render with card structure
- should have gradient header
- should display BookOpen icon in header
- should use grid layout for top fields
- should have proper spacing
- should style textarea with resize-none
- Accessibility
- should have proper labels for all inputs
- should have semantic heading
- should have keyboard navigable elements
- Props Handling
- should update when props change
- should call different onChange callbacks
- Edge Cases
- should handle very long interests text
- should handle very long learning objectives
- should handle boundary values for weekly hours
- should not call onChange on initial render
- should maintain state consistency with external updates
- Weekly Hours Validation
- should accept valid numbers within range (1-40)
- should reject value over 40
- should allow clearing the field
- should accept minimum boundary value (1)
- should accept maximum boundary value (40)
- should prevent typing e, +, -, and . characters
- Rendering
File: frontend/components/admin/user-edit/tests/LocationSection.test.tsx
- LocationSection Component
- Rendering
- should render section title with icon
- should render country input field
- should render city input field
- should render timezone input field
- should render all three fields
- Country Input
- should display empty country by default
- should display provided country value
- should have placeholder text
- should call onChange when country is typed
- should call onChange when country is cleared
- should handle special characters in country name
- City Input
- should display empty city by default
- should display provided city value
- should have placeholder text
- should call onChange when city is typed
- should call onChange when city is cleared
- Timezone Input
- should display empty timezone by default
- should display provided timezone value
- should have placeholder text
- should call onChange when timezone is typed
- should call onChange when timezone is cleared
- should handle timezone format with slashes
- Combined Interactions
- should handle changes to all three fields independently
- should handle interleaved changes
- Styling and Structure
- should render with card structure
- should have gradient header
- should display Globe icon in header
- should use grid layout for fields
- should have proper spacing between fields
- should style inputs consistently
- Accessibility
- should have proper labels for all inputs
- should have semantic heading
- should have keyboard navigable elements
- should associate inputs with labels
- Props Handling
- should update when country prop changes
- should update when city prop changes
- should update when timezone prop changes
- should call different onChange callbacks
- Edge Cases
- should handle very long country names
- should handle very long city names
- should handle complex timezone strings
- should maintain state consistency with external updates
- should not call onChange on initial render
- should handle copy-paste operations
- should handle numeric input in text fields
- Rendering
File: frontend/components/admin/user-edit/tests/RoleStatusSection.test.tsx
- RoleStatusSection Component
- Rendering
- should render section title with icon
- should render role select field
- should render profile completed checkbox
- Role Selection
- should display current role value
- should render all role options
- should show confirmation dialog when role is changed to ADMIN
- should call onChange when admin confirmation is accepted
- should not call onChange when admin confirmation is cancelled
- should call onChange when role is changed to PREMIUM
- should call onChange when role is changed to FREE
- should handle rapid role changes (non-ADMIN)
- should require confirmation for each change to ADMIN role
- Profile Completed Checkbox
- should display unchecked when profileCompleted is false
- should display checked when profileCompleted is true
- should call onChange when checkbox is checked
- should call onChange when checkbox is unchecked
- should toggle checkbox on label click
- should call onChange on each checkbox click
- Combined Interactions
- should handle both role change and checkbox toggle independently
- should handle interleaved role and status changes
- should handle interleaved role and status changes with ADMIN confirmation
- Styling and Structure
- should render with card structure
- should have gradient header
- should display Shield icon in header
- should use grid layout for fields
- should have proper spacing between fields
- should style select with border focus
- should style checkbox properly
- should have cursor pointer on checkbox label
- Accessibility
- should have proper label for role select
- should have proper label for checkbox
- should have semantic heading
- should associate role select with label
- should have keyboard navigable elements
- Props Handling
- should update when role prop changes
- should update when profileCompleted prop changes
- should call different onChange callbacks
- Edge Cases
- should handle all role values correctly
- should maintain state consistency with external updates
- should not call onChange on initial render
- Rendering
File: frontend/components/admin/user-edit/tests/UserEditFlow.integration.test.tsx
- User Edit Flow Integration Tests
- Complete Success Flow: Fetch → Display → Edit → Submit → Success
- should complete the full user edit flow successfully
- should handle editing multiple fields and submit all changes
- should parse comma-separated interests and learning objectives correctly
- Admin Role Confirmation Dialog Flow
- should show confirmation dialog when changing to ADMIN role
- should complete user update when admin confirmation is accepted
- should revert role change when admin confirmation is cancelled
- should handle multiple admin confirmation attempts
- Form Validation
- should prevent entering weekly_learning_hours less than 1
- should prevent entering weekly_learning_hours greater than 40
- should accept weekly_learning_hours at boundary values (1 and 40)
- should prevent entering non-numeric weekly_learning_hours
- should allow empty weekly_learning_hours (optional field)
- should clear error message when form is edited after API failure
- Error Handling
- should display error message when getUser API fails
- should display error message when updateUser API fails
- should display custom error message from API
- should re-enable save button after API error
- should allow retry after API error
- should clear error message when making new edits
- Loading States
- should show loading state on initial render
- should transition from loading to form display
- should show saving state during form submission
- should prevent multiple simultaneous submissions
- Accessibility
- should have accessible loading state
- should have accessible error messages
- should have accessible success messages
- should maintain focus management during form submission
- Edge Cases
- should handle user with minimal data (only required fields)
- should handle rapid form field changes before submit
- should handle empty comma-separated fields correctly
- should trim whitespace from comma-separated values
- Complete Success Flow: Fetch → Display → Edit → Submit → Success
File: frontend/components/admin/user-edit/tests/UserInfoCard.test.tsx
- UserInfoCard Component
- Rendering
- should render the card with title
- should display user email
- should display user name
- should display cognito sub
- should display joined date
- should display last updated date
- Empty or Missing Data
- should display dash when name is empty
- should display dash when name is null
- should display dash when name is undefined
- Date Formatting
- should format created_at date correctly
- should format updated_at date correctly
- should include time in date format
- should handle different date formats
- Styling and Structure
- should render with proper card structure
- should have gradient header
- should display cognito sub in monospace font
- should break long cognito sub text
- should have consistent spacing between fields
- should use proper text colors for labels
- should use proper text colors for values
- Accessibility
- should have semantic HTML structure
- should have proper heading hierarchy
- should associate labels with values visually
- Edge Cases
- should handle very long email addresses
- should handle very long names
- should handle very long cognito sub
- should handle special characters in name
- should handle dates with milliseconds
- should handle dates at year boundaries
- Component Props
- should accept and render different users
- should update when user prop changes
- Read-only Nature
- should not contain any input elements
- should not contain any editable content
- Rendering
File: frontend/components/analytics/tests/ActivityChart.test.tsx
- ActivityChart
- Lessons metric
- should render chart with lessons data
- should display Y-axis label for lessons
- should render bars for each data point
- Time metric
- should render chart with time data
- should display Y-axis label for time
- Empty data
- should display message when no data available
- should not render SVG when no data
- Axis visibility
- should show X-axis when showXAxis is true
- should show Y-axis when showYAxis is true
- Custom height
- should respect custom height prop
- Gradient
- should include gradient definition for bars
- Lessons metric
File: frontend/components/badges/tests/BadgeCard.test.tsx
- BadgeCard
- renders badge information correctly
- shows earned date when badge is earned
- shows lock icon for unearned badges
- shows progress bar when showProgress is true and badge is unearned
- calls onShowcaseToggle when showcase button is clicked
- shows
- applies correct tier styling for GOLD badge
- applies correct tier styling for PLATINUM badge
File: frontend/components/badges/tests/StatisticsCard.test.tsx
- StatisticsCard
- renders all statistics correctly
- formats time spent correctly in hours and minutes
- formats time spent correctly when less than an hour
- shows rank when showRank is true
- does not show rank when showRank is false
- renders Your Statistics heading
- displays all stat labels
File: frontend/components/courses/tests/CourseCard.test.tsx
- CourseCard Component
- Rendering
- should render course title
- should render course description
- should render course category
- should render course duration
- should render number of lessons
- should render number of students with proper formatting
- should render course rating
- should render
- Link Behavior
- should render as a link to the course detail page
- should use correct course ID in the link
- Image Display
- should set background image using course imageUrl
- should have proper image container styling
- Icons and Visual Elements
- should render TrendingUp icon
- should render Clock icon for duration
- should render star rating icon
- should render ArrowRight icon in CTA
- Styling and Layout
- should have proper card styling
- should have hover effects
- should have border styling
- should apply line-clamp to description
- should have proper padding in info section
- Data Display Formatting
- should format large student numbers with locale string
- should display single-digit duration correctly
- should display two-digit duration correctly
- should display decimal ratings correctly
- should display whole number ratings correctly
- Accessibility
- should have accessible link
- should contain course title for screen readers
- should have semantic heading for title
- Edge Cases
- should handle course with no students
- should handle course with very long title
- should handle course with very long description
- should handle course with special characters in category
- should handle missing or empty imageUrl gracefully
- should handle single lesson course
- should handle minimum rating (0)
- should handle maximum rating (5)
- Hover Effects
- should have title color transition on hover
- should have image overlay transition
- should have icon scale effect on hover
- should have CTA gap transition on hover
- Content Structure
- should render category badge at top of image
- should render duration badge at bottom of image
- should display lessons and students in the same row
- should display rating and CTA in the same row
- Rendering
File: frontend/components/dashboard/tests/ActiveCoursesSection.test.tsx
- ActiveCoursesSection Component
- Loading State
- should show loading spinner initially
- should show loading title
- should show spinner animation
- Authenticated User with Enrollments
- should display user enrollments
- should render EnrolledCourseCard for each enrollment
- should show
- should call getUserEnrollments with correct parameters
- Authenticated User with No Enrollments
- should use mock data when no enrollments
- should show
- Unauthenticated User (Mock Data)
- should show mock data when user is not authenticated
- should not call API when user is not authenticated
- Error Handling
- should display error UI when API fails
- should display error icon in error UI
- should not show mock data when error UI is displayed
- should log error to console when API fails
- Mock Data Display
- should use mock data when API returns empty enrollments
- should show Browse More Courses button with mock data
- Component Lifecycle
- should fetch enrollments on mount
- should handle user changes
- Edge Cases
- should handle single enrollment
- should handle many enrollments
- should handle enrollment without course title
- Accessibility
- should have heading for section title
- should have accessible button for browsing courses
- Loading State
File: frontend/components/dashboard/tests/DashboardTabs.test.tsx
- DashboardTabs Component
- Rendering
- should render all four tabs
- should render icons for each tab
- Active Tab Styling
- should highlight learning tab when active
- should highlight progress tab when active
- should highlight profile tab when active
- should highlight recommendations tab when active
- should not highlight inactive tabs
- Tab Click Handling
- should call onTabChange with
- should call onTabChange with
- should call onTabChange with
- should call onTabChange with
- should call onTabChange only once per click
- Layout and Structure
- should have sticky positioning
- should have correct z-index
- should have white background
- should have border styling
- Tab Order
- should render tabs in correct order
- Accessibility
- should have clickable buttons for each tab
- should have transition effects on buttons
- Type Safety
- should accept valid DashboardTab values
- Rendering
File: frontend/components/dashboard/tests/LearningTab.test.tsx
- LearningTab Component
- Rendering
- should render the ActiveCoursesSection
- should render the motivation card
- should render the learning tips card
- should render all four learning tips
- Layout
- should have a grid layout with 3 columns on large screens
- should have main content spanning 2 columns
- should have gap between grid items
- Motivation Card Styling
- should have gradient background
- should have left border accent
- should have rounded corners
- Tips Card Styling
- should have white background
- should have border styling
- Sidebar
- should have space between sidebar items
- Does Not Render Recommendations
- should not render RecommendedCoursesSection (moved to separate tab)
- Rendering
File: frontend/components/dashboard/tests/ProfileTab.test.tsx
- ProfileTab Component
- Loading State
- should show loading spinner initially
- should show loading spinner with animation
- Statistics Display
- should display statistics section after loading
- should display total points
- should display badges earned count
- should display current streak
- should display longest streak
- should display courses completed
- should display time learning formatted correctly
- Share Profile Button
- should render share profile button
- should call clipboard copy when clicked (when share API not available)
- Badge Tabs
- should render Earned Badges tab
- should render In Progress tab
- should show earned badges count
- should show in progress badges count
- should switch to progress tab when clicked
- BadgeGrid Integration
- should render BadgeGrid component
- should pass earned badges to BadgeGrid on earned tab
- Motivation Section
- should render motivation section
- should have motivational message
- should have gradient background styling
- Layout
- should have vertical spacing between sections
- should have responsive statistics grid
- API Calls
- should fetch statistics and badge progress on mount
- should include authorization header
- Error Handling
- should handle API errors gracefully
- Loading State
File: frontend/components/dashboard/tests/ProgressTab.test.tsx
- ProgressTab Component
- Loading State
- should show loading spinner when isLoading is true
- should show loading spinner with animation
- Error State
- should show error message when error is provided
- should show default error when analytics is null without error message
- should have error styling
- Rendering with Analytics
- should render overall stats grid
- should display correct analytics values
- should render Activity Overview section
- should render ActivityChart
- should render Course Progress section
- should display course progress items
- should show course completion percentages
- should show lesson counts
- Streak Card
- should render streak section
- should display current streak
- should display longest streak
- should display last activity date
- Milestones
- should render milestones section
- should show 10 Lessons milestone when completed 10+ lessons
- should show 7 Day Streak milestone when current streak >= 7
- should show Course Complete milestone when completed >= 1 course
- should show unlock message when no milestones achieved
- Chart Controls
- should render metric toggle buttons
- should toggle chart metric when clicked
- should render time range buttons
- Empty Course List
- should show empty message when no courses
- Layout
- should have grid layout with 3 columns on large screens
- should have main content spanning 2 columns
- Loading State
File: frontend/components/dashboard/tests/RecommendationsTab.test.tsx
- RecommendationsTab Component
- Rendering
- should render the personalized header
- should render the header description
- should render the RecommendedCoursesSection
- should render the tips section
- should render all recommendation criteria
- Layout
- should have vertical spacing between sections
- Header Card Styling
- should have gradient background
- should have border styling
- should have rounded corners
- should have icon with gradient background
- Tips Card Styling
- should have white background
- should have border styling
- should have icon with green gradient
- List Items
- should render four recommendation criteria as list items
- should have proper spacing between list items
- Icons
- should render Sparkles icon in header
- should render TrendingUp icon in tips section
- Accessibility
- should have heading hierarchy
- should have proper text sizing for headings
- Rendering
File: frontend/components/dashboard/progress/tests/ActivityChartSection.test.tsx
- ActivityChartSection
- Rendering
- should render the section title
- should render the ActivityChart component
- should pass correct data to ActivityChart
- should render with correct background and styling
- Metric Toggle
- should render lessons and time metric buttons
- should highlight lessons button when lessons metric is selected
- should highlight time button when time metric is selected
- should call setChartMetric with lessons when lessons button is clicked
- should call setChartMetric with time when time button is clicked
- should update chart metric display when toggled
- Time Range Toggle
- should render all three time range buttons
- should highlight 30d button when 30 days is selected
- should highlight 60d button when 60 days is selected
- should highlight 90d button when 90 days is selected
- should call setTimeRange with 30 when 30d button is clicked
- should call setTimeRange with 60 when 60d button is clicked
- should call setTimeRange with 90 when 90d button is clicked
- Toggle Group Styling
- should render metric toggle with correct background
- should style inactive buttons correctly
- should apply transition classes to all buttons
- Icon
- should render the BarChart3 icon
- should have gradient background for icon container
- Layout
- should have responsive header layout
- should wrap toggle controls on mobile
- Combined Toggles
- should handle metric and time range changes independently
- should maintain independent state for both toggles
- Multiple Clicks
- should handle multiple metric toggle clicks
- should handle multiple time range toggle clicks
- should allow clicking the same button multiple times
- Accessibility
- should have accessible button elements
- should have visible text labels
- should have proper font sizing for buttons
- should have aria-label attributes on toggle buttons
- should have aria-pressed attribute on active toggle button
- should update aria-pressed when metric toggle changes
- should have role=
- should have aria-label on toggle group containers
- Edge Cases
- should render with empty activity data
- should handle rapid toggle switching
- should maintain consistent button order
- Rendering
File: frontend/components/dashboard/progress/tests/CourseProgressList.test.tsx
- CourseProgressList
- Rendering
- should render the section title
- should render all courses
- should render with correct background and styling
- should render BookOpen icon
- Empty State
- should show empty message when no courses
- should not show course cards when empty
- should center empty state message
- should have proper styling for empty state
- Course Cards
- should display course titles
- should display completion percentages
- should display lesson counts
- should display time spent
- should have proper spacing between cards
- should have hover effects on cards
- Progress Bars
- should render progress bars for each course
- should set correct width for 80% completion
- should set correct width for 50% completion
- should set correct width for 100% completion
- should handle 0% completion
- should have gradient styling
- Card Layout
- should have proper card structure
- should display title and percentage in the same row
- should display lesson count and time in the same row
- Single Course
- should render correctly with one course
- should not show empty state with one course
- Time Formatting
- should format seconds correctly
- should format minutes correctly
- should format hours correctly
- should format hours and minutes correctly
- Text Styling
- should have bold course titles
- should have colored completion percentages
- should have muted info text
- Edge Cases
- should handle course with no time spent
- should handle course with very long title
- should handle course with 0 total lessons
- should handle fractional completion percentages
- should handle very large time values
- Accessibility
- should have visible course information
- should maintain proper contrast for text
- Course Order
- should maintain the order of courses as provided
- should handle reversed order
- Rendering
File: frontend/components/dashboard/progress/tests/MilestonesCard.test.tsx
- MilestonesCard
- Rendering
- should render the card title
- should render Award icon
- should have white background with border
- Empty State
- should show empty message when no milestones achieved
- should not show milestone items when hasAnyMilestone is false
- should center empty state message
- should style empty message with gray color
- Lesson Milestone
- should display lesson milestone when achieved
- should not display lesson milestone when not achieved
- should display target emoji (🎯)
- should have amber styling
- Streak Milestone
- should display streak milestone when achieved
- should not display streak milestone when not achieved
- should display fire emoji (🔥)
- should have orange styling
- Course Complete Milestone
- should display course milestone when achieved
- should not display course milestone when not achieved
- should display graduation cap emoji (🎓)
- should have green styling
- Multiple Milestones
- should display all three milestones when all achieved
- should display only lesson and streak milestones
- should display only lesson and course milestones
- should display only streak and course milestones
- should display all three emojis when all milestones achieved
- should not show empty state when any milestone is achieved
- Milestone Order
- should display milestones in correct order: lesson, streak, course
- should maintain order even when some are missing
- Styling
- should have proper spacing between milestones
- should have border-left styling for all milestones
- should have rounded corners for milestones
- should have large emoji text
- should have bold milestone titles
- should have small muted description text
- Layout
- should have header with icon and title
- should have proper padding for milestones
- should align items with flexbox
- hasAnyMilestone Flag
- should show empty state when hasAnyMilestone is false and no individual milestones
- should show milestones when hasAnyMilestone is true and individual milestones exist
- should hide empty state when hasAnyMilestone is true
- Icon Container
- should have gradient background for main icon
- should have correct sizing for icon container
- should center icon in container
- Accessibility
- should have visible milestone titles
- should have visible descriptions
- should have proper contrast for text
- should have readable font sizes
- Edge Cases
- should handle single milestone (lesson only)
- should handle single milestone (streak only)
- should handle single milestone (course only)
- should render consistently on multiple renders
- Rendering
File: frontend/components/dashboard/progress/tests/OverallStatsGrid.test.tsx
- OverallStatsGrid
- Rendering
- should render all four stat cards
- should render in a grid layout
- Total Courses Stat
- should display correct number of courses
- should display zero courses
- should display large number of courses
- should have correct icon and styling
- Lessons Done Stat
- should display correct number of lessons
- should display zero lessons
- should display large number of lessons
- Time Invested Stat
- should display hours when time is in hours
- should display minutes when time is less than 1 hour
- should display hours when both hours and minutes exist
- should display zero minutes
- should display large hour values
- should prefer hours display over minutes
- Avg Completion Stat
- should display completion rate rounded to nearest integer
- should round down when decimal is below .5
- should round up when decimal is .5 or above
- should display 0% for zero completion
- should display 100% for full completion
- Styling
- should have correct card styling classes
- should have gradient backgrounds for icons
- should have hover effects
- Icons
- should render all four icons
- should have correct icon colors (white)
- Edge Cases
- should handle very large numbers
- should handle decimal completion rates correctly
- should handle negative values gracefully (edge case)
- Accessibility
- should have readable text labels
- should have proper text contrast classes
- Rendering
File: frontend/components/dashboard/progress/tests/ProgressTab.test.tsx
- ProgressTab (Refactored)
- Loading State
- should show loading spinner when isLoading is true
- should show loading spinner with animation
- should not render child components when loading
- should center loading content
- should have proper text color for loading message
- Error State
- should show error message when error is provided
- should show default error when analytics is null without error message
- should have error styling with red background
- should have red text color for error message
- should not render child components when error exists
- should prioritize error over analytics when both exist
- Successful Rendering
- should render all main sections when analytics is loaded
- should not show loading or error states
- should have grid layout with 3 columns on large screens
- should have main content column spanning 2 columns
- should have sidebar column
- Component Integration
- should pass analytics to OverallStatsGrid
- should pass totalTime from hook to OverallStatsGrid
- should pass timeRange and chartMetric to ActivityChartSection
- should pass courses to CourseProgressList
- should pass streaks to StreakCard
- should pass milestones to MilestonesCard
- Hook Integration
- should call useProgressStats hook with analytics
- should call useProgressStats hook with null when analytics is null
- should use hook values for state management
- Interactive Functionality
- should pass setTimeRange function to ActivityChartSection
- should pass setChartMetric function to ActivityChartSection
- Layout Structure
- should have main content area with proper spacing
- should render components in correct order in main content
- should render components in correct order in sidebar
- Edge Cases
- should handle analytics with empty courses array
- should handle analytics with empty activity array
- should handle analytics with zero streaks
- should handle transition from loading to success
- should handle transition from success to error
- should handle loading priority over error
- Responsive Design
- should have responsive grid classes
- should have responsive column span for main content
- should have proper gap spacing
- Performance
- should not re-render unnecessarily when props do not change
- Component Isolation
- should render each section independently
- should pass correct props to each section
- Loading State
File: frontend/components/dashboard/progress/tests/StreakCard.test.tsx
- StreakCard
- Rendering
- should render the card title
- should render current streak label and value
- should render longest streak label and value
- should have gradient background
- should render Flame icon
- Streak Values
- should display zero current streak
- should display single day streak
- should display large current streak
- should display zero longest streak
- should display large longest streak
- should handle current streak equal to longest streak
- should handle current streak greater than longest streak (edge case)
- Last Activity Date
- should display last activity date when provided
- should format date correctly
- should not display last activity section when date is null
- should render Calendar icon when date is present
- should not render Calendar icon when date is null
- Styling
- should have white text color
- should have rounded corners
- should have proper padding
- should have backdrop blur on stat containers
- should have gradient background for stat containers
- should have large bold text for streak values
- should have small muted text for labels
- Layout
- should have proper spacing between sections
- should have header with icon and title
- should have border separator when last activity exists
- should not have border separator when last activity is null
- Icon Styling
- should have orange flame icon with border
- should have correct icon sizing
- should center icon in container
- Date Formatting Edge Cases
- should handle date at start of year
- should handle date at end of year
- should handle leap year date
- should handle past dates
- should handle future dates
- Accessibility
- should have visible labels
- should have visible values
- should have sufficient color contrast with white text
- should have readable font sizes
- Edge Cases
- should handle negative streak values gracefully
- should handle very large streak numbers
- should handle empty string for last activity date
- should render all content with minimum data
- Text Content
- should use
- should have consistent text formatting
- should include
- Rendering
File: frontend/components/enrollment/tests/EnrollButton.test.tsx
- EnrollButton Component
- Initial State - Unauthenticated User
- should show
- should show price for paid course
- should redirect to signin when clicked
- Initial State - Authenticated User
- should check enrollment status on mount
- should show checking status initially
- should show enroll button after check completes
- should show enrolled state when already enrolled
- should disable button while checking enrollment
- Free Course Enrollment
- should enroll in free course successfully
- should show processing state during enrollment
- should disable button during enrollment
- should handle enrollment error
- should handle non-Error exceptions
- should call onEnrollmentChange callback on successful enrollment
- Paid Course Enrollment
- should create checkout session for paid course
- should store checkout session in localStorage
- should redirect to checkout page
- should show money-back guarantee text
- should not show guarantee text for free courses
- should handle checkout session creation error
- should handle non-Error checkout exceptions
- Already Enrolled State
- should show
- should disable button when already enrolled
- should redirect to dashboard when clicked
- should show CheckCircle icon when enrolled
- Enrollment Check Error Handling
- should handle enrollment check error
- should handle non-Error check exceptions
- should handle API returning error in response
- Component Props
- should apply custom variant
- should apply custom size
- should apply fullWidth prop
- should apply custom className
- should use default props when not specified
- Component Lifecycle
- should cleanup on unmount
- Edge Cases
- should handle price of 0.01
- should handle large price values
- should handle very long course names
- should handle rapid clicks
- Initial State - Unauthenticated User
File: frontend/components/enrollment/tests/EnrolledCourseCard.test.tsx
- EnrolledCourseCard Component
- Rendering - Basic Information
- should render course title from courseDetails
- should render course title from enrollment when courseDetails not provided
- should render category badge
- should render default category when not provided
- should render enrollment date
- Progress Display
- should display current day and total days
- should display progress percentage
- should render progress bar with correct width
- should calculate progress correctly for 0% completion
- should calculate progress correctly for 100% completion
- should handle enrollment with no completed_lessons
- should handle enrollment with no total_lessons
- Incomplete Course State
- should show
- should show next lesson day
- should show lesson duration estimate
- should show
- should link to correct lesson
- should show Play icon when not completed
- Completed Course State
- should show completed badge
- should not show
- should not show
- should show
- should link to first lesson for review
- should show congratulations message
- should show completion emoji
- should show CheckCircle icon when completed
- Different Duration Courses
- should handle 14-day course
- should handle 21-day course
- Edge Cases
- should handle enrollment without courseDetails
- should handle enrollment without course_title
- should cap current day at total lessons
- should handle zero total lessons gracefully
- should format enrollment date correctly
- Styling and Layout
- should have card container with proper classes
- should have hover effect classes
- should have gradient icon background
- should have category badge styling
- should have progress bar gradient
- Button Props
- should render Continue Learning button with correct props
- should render Review Course button with correct props when completed
- Accessibility
- should have course title as heading
- should have accessible button
- Progress Calculation Edge Cases
- should handle fractional progress percentages
- should handle near-completion progress
- should not show completed badge when at 99%
- Rendering - Basic Information
File: frontend/components/layout/tests/Header.test.tsx
- Header Component
- Rendering
- should render the header with brand logo and name
- should render desktop navigation links
- should render the Zap icon in the logo
- should have sticky positioning class
- Navigation Links
- should have correct href for Courses link
- should have correct href for Dashboard link
- should have correct href for brand logo
- should not render Profile link (removed)
- should not render Analytics link (removed)
- Active Link Highlighting
- should highlight home link when activeLink is
- should highlight courses link when activeLink is
- should highlight dashboard link when activeLink is
- Mobile Menu
- should render mobile menu button
- should show mobile menu when menu button is clicked
- should hide mobile menu when close button is clicked
- should show navigation links in mobile menu
- should close mobile menu when a link is clicked
- should show user info in mobile menu when authenticated
- should show sign in/sign up buttons in mobile menu when not authenticated
- User Authentication Display
- should show Sign In and Start Free Trial buttons when not authenticated
- should show user avatar when authenticated
- should show Sign Out button when authenticated
- should call signOut when Sign Out button is clicked
- Admin Link
- should show Admin Panel link when user is admin
- should not show Admin Panel link when user is not admin
- should show Admin Panel link in mobile menu when user is admin
- Styling and Layout
- should have proper container styling
- should have white background with border
- should have backdrop blur effect
- should have gradient text for brand name
- should hide desktop nav on mobile
- should show mobile menu button only on mobile
- Accessibility
- should have proper navigation landmark
- should have header landmark
- should have accessible mobile menu button
- should toggle aria-label on mobile menu button
- Responsive Design
- should have responsive padding
- should have responsive logo sizing
- should have responsive brand text sizing
- Rendering
File: frontend/components/recommendations/tests/RecommendedCoursesSection.test.tsx
- RecommendedCoursesSection Component
- Loading State
- should show loading skeletons initially
- should show loading skeletons for authenticated user
- should show loading skeletons for anonymous user
- Personalized Recommendations for Authenticated Users
- should fetch and display personalized recommendations
- should show
- should call getPersonalizedRecommendations with correct limit
- should show recommendation reasons
- should show
- Popular Courses for Anonymous Users
- should fetch and display popular courses
- should not show
- should call getPopularCourses with correct limit
- Error Handling
- should show error message when personalized recommendations fail
- should show error message when popular courses fail
- should log error to console
- Empty State
- should not render when no recommendations
- Component Lifecycle
- should fetch recommendations on mount for authenticated user
- should fetch recommendations on mount for anonymous user
- should refetch when user authentication changes
- Accessibility
- should render CourseCard for each recommendation
- Loading State
File: frontend/components/recommendations/tests/SimilarCoursesSection.test.tsx
- SimilarCoursesSection Component
- Loading State
- should show loading spinner initially
- should show loading skeletons
- should show section title during loading
- should show section title during loading
- Similar Courses Display
- should fetch and display similar courses
- should call getSimilarCourses with correct courseId
- should call getSimilarCourses with custom limit
- should render CourseCard for each similar course
- should show section heading
- should show section subtitle
- Error Handling
- should not render when API fails (silent failure)
- should log error to console
- should not show error message to user
- Empty State
- should not render when no similar courses
- should not render when API returns empty array
- Component Lifecycle
- should fetch similar courses on mount
- should refetch when courseId changes
- should refetch when limit changes
- Edge Cases
- should handle single similar course
- should handle many similar courses
- should handle courseId with special characters
- should handle zero limit gracefully
- Accessibility
- should have heading for section title
- should render with proper semantic structure
- Performance
- should not refetch when unrelated props change
- Loading State
File: frontend/components/ui/tests/Button.test.tsx
- Button Component
- Rendering
- should render with children text
- should render as a link when href is provided
- should render with default variant (primary)
- should render with default size (md)
- should render with default type (button)
- Variants
- should render primary variant with correct styles
- should render secondary variant with correct styles
- should render outline variant with correct styles
- should render ghost variant with correct styles
- Sizes
- should render small size with correct styles
- should render medium size with correct styles
- should render large size with correct styles
- States
- should apply disabled styles when disabled
- should not be disabled by default
- should apply full width styles when fullWidth is true
- should not apply full width styles by default
- Button Types
- should render with submit type
- should render with reset type
- Custom Styling
- should apply custom className
- should merge custom className with default styles
- Interactions
- should call onClick handler when clicked
- should not call onClick when disabled
- should not call onClick when rendered as link
- Accessibility
- should be keyboard accessible
- should have proper button role
- should have proper link role when href is provided
- Edge Cases
- should render with multiple children elements
- should handle empty children
- should render with all props combined
- Rendering
File: frontend/hooks/tests/useCourseFilters.test.ts
- useCourseFilters Hook
- Initialization
- should initialize with default values
- should return all courses when no filters are applied
- should handle empty course array
- Search Query Filter
- should filter courses by title (case insensitive)
- should filter courses by description (case insensitive)
- should handle uppercase search query
- should handle mixed case search query
- should return empty array when no matches found
- should handle empty search query
- should handle whitespace-only search query
- should handle partial word matches
- Category Filter
- should filter courses by category
- should filter courses by Wellness category
- should filter courses by Communication category
- should return all courses when
- should return empty array for non-existent category
- Duration Filter
- should filter courses by 7 days duration
- should filter courses by 14 days duration
- should filter courses by 21 days duration
- should return all courses when
- should return empty array for non-existent duration
- Combined Filters
- should apply search and category filters together
- should apply search and duration filters together
- should apply category and duration filters together
- should apply all three filters together
- should return empty array when combined filters have no matches
- Filter State Updates
- should update search query state
- should update category state
- should update duration state
- should handle multiple sequential updates
- Memoization
- should not recompute filtered courses when unrelated state changes
- should recompute when search query changes
- should recompute when category changes
- should recompute when duration changes
- Edge Cases
- should handle courses with special characters in title
- should handle courses with special characters in description
- should handle clearing filters
- should maintain filter state when course list changes
- Return Object Structure
- should return all expected properties
- should return functions for all setters
- should return array for filteredCourses
- Initialization
File: frontend/hooks/tests/useCourseForm.test.ts
- useCourseForm Hook
- Initial State - No Course Provided
- should initialize with empty form data when no course is provided
- should initialize with empty learning objectives
- should initialize with empty requirements
- should not be submitting initially
- should have no error initially
- Initial State - With Course Provided
- should initialize with course data when course is provided
- should initialize with learning objectives from course metadata
- should initialize with requirements from course metadata
- should filter out non-string values from whatYouWillLearn array
- should filter out non-string values from requirements array
- should handle invalid metadata gracefully (non-array whatYouWillLearn)
- should handle missing metadata gracefully
- Category Loading
- should load categories from API on mount
- should set isLoadingCategories to true while loading
- should set categories from API response
- should set isLoadingCategories to false after loading
- should use fallback categories when API returns empty array
- should use fallback categories when API throws error
- should log error when API fails
- handleChange - Form Field Updates
- should update title field
- should update description field
- should update category_id field
- should update duration_days field as number
- should update price field as number
- should update thumbnail field
- should update status field
- should handle multiple field updates
- should convert duration_days to 7, 14, or 21
- Learning Objectives Management
- should set new learning objective
- should add learning objective when handleAddLearningObjective is called
- should trim whitespace when adding learning objective
- should not add empty learning objective
- should not add whitespace-only learning objective
- should add multiple learning objectives
- should remove learning objective by ID
- should remove first learning objective
- should remove last learning objective
- should handle removing non-existent ID from learning objectives array
- Requirements Management
- should set new requirement
- should add requirement when handleAddRequirement is called
- should trim whitespace when adding requirement
- should not add empty requirement
- should not add whitespace-only requirement
- should add multiple requirements
- should remove requirement by ID
- should remove last requirement
- should handle removing non-existent ID from requirements array
- Form Submission - Success Cases
- should call onSubmit with correct data
- should include learning objectives in metadata
- should include requirements in metadata
- should preserve instructor metadata when updating course
- should not include instructor in metadata if not present in original course
- should set isSubmitting to true during submission
- should clear error when submitting successfully
- should call preventDefault on form event
- Form Submission - Error Handling
- should set error message when submission fails with Error
- should set generic error message when submission fails with non-Error
- should set isSubmitting to false after error
- should handle network errors gracefully
- should handle validation errors
- Metadata Preservation and Security
- should only preserve instructor field from existing metadata
- should not include undefined instructor in metadata
- Edge Cases and Complex Scenarios
- should handle rapid field changes
- should handle adding and removing learning objectives in sequence
- should handle zero price
- should handle decimal price values
- should handle empty thumbnail URL
- should maintain state consistency across multiple operations
- Hook Stability and Performance
- should maintain stable callback references for handlers
- should only fetch categories once on mount
- Initial State - No Course Provided
File: frontend/hooks/tests/useCourseGenerationForm.test.ts
- useCourseGenerationForm Hook
- Initialization
- should initialize with default form data
- should initialize with empty learning objectives
- should initialize with default duration of 14 days
- should initialize with default tone as friendly
- should initialize with generateVideo as true
- should initialize with isAsync as false
- should initialize with no PDF file
- should initialize with no error
- should initialize with empty objective input
- should initialize with isSubmitting as false
- Category Loading
- should load categories from API on mount
- should set isLoadingCategories to true initially
- should set isLoadingCategories to false after loading
- should use fallback categories when API fails
- should use fallback categories with slug as id
- should keep fallback categories when API returns empty array
- Learning Objectives
- should add learning objective when addObjective is called
- should trim whitespace from objectives
- should not add empty objectives
- should not add objectives when max limit is reached
- should remove learning objective at specified index
- should clear objective input after adding
- should allow adding objectives up to max limit of 6
- PDF Upload
- should handle valid PDF upload
- should reject non-PDF files
- should reject files larger than 4MB
- should handle upload event with no files
- should remove PDF file
- should clear error when valid PDF is uploaded
- Form Submission
- should submit form with correct data
- should set isSubmitting to false after submission
- should include learning objectives in submission
- should include reference materials in submission
- should handle submission error
- should include PDF file info when submitting with PDF
- should include generation options in submission
- should clear error before submission
- Form Data Updates
- should update form data with setFormData
- should update duration_days
- should update difficultyLevel
- should update tone
- should update isAsync
- should update generateVideo
- Error Handling
- should set error with setError
- should clear error with setError(null)
- Return Object Structure
- should return all expected properties
- should return functions for all handlers
- Initialization
File: frontend/hooks/tests/useLessonForm.test.ts
- useLessonForm Hook
- Initial State
- Create Mode (no lesson provided)
- should initialize with empty form data
- should initialize with single empty action item with unique ID
- should have isSubmitting as false
- should have isGenerating as false
- should have no error message
- should have no success message
- Edit Mode (with existing lesson)
- should initialize form data with lesson values
- should initialize action items with lesson action items and unique IDs
- should handle lesson with no action items by creating empty default
- should handle lesson with undefined video_url
- should handle lesson with undefined generation_prompt
- Create Mode (no lesson provided)
- Form Field Updates
- handleChange
- should update string field (title)
- should update string field (course_id)
- should update number field (day) and convert to number
- should update number field (order_index) and convert to number
- should update video_url field
- should update generation_prompt field
- should not mutate other form fields when updating one field
- handleContentChange
- should update content field with rich text
- should update content field with plain text
- should update content field with empty string
- should not mutate other form fields when updating content
- handleChange
- Action Items Management
- handleActionItemChange
- should update action item by ID
- should update second action item without affecting first
- should handle updating action item to empty string
- should update action item with special characters
- should preserve item ID when updating value
- addActionItem
- should add new empty action item with unique ID
- should preserve existing action items when adding new one
- should allow adding multiple action items with unique IDs
- removeActionItem
- should remove action item by ID
- should remove second action item correctly
- should handle removing from middle of three items
- should allow removing all items
- handleActionItemChange
- Form Submission
- handleSubmit - Success Cases
- should call onSubmit with form data
- should filter out empty action items before submitting
- should filter out whitespace-only action items and trim values
- should submit with empty action_items array if all are empty
- should clear error message on successful submit
- handleSubmit - Error Handling
- should set error message when onSubmit throws Error
- should set generic error message when onSubmit throws non-Error
- should set isSubmitting to false after error
- should handle validation error from API
- handleSubmit - Loading States
- should set isSubmitting to true during submission
- should reset isSubmitting to false on success
- handleSubmit - Success Cases
- AI Lesson Generation
- handleGenerateLesson - Success Cases
- should call regenerateLesson API with lesson ID and prompt
- should call regenerateLesson with undefined when prompt is empty
- should update generation_prompt in formData after successful generation
- should set success message after generation
- should clear error message on successful generation
- should clear success message on new generation
- handleGenerateLesson - Error Cases
- should not call API when lesson ID is not available
- should set error message when regenerateLesson throws Error
- should set generic error message when regenerateLesson throws non-Error
- should not set success message when generation fails
- should set isGenerating to false after error
- handleGenerateLesson - Loading States
- should set isGenerating to true during generation
- should set isGenerating to false after successful generation
- handleGenerateLesson - Success Cases
- Hook Return Values
- should return all expected properties
- should return functions that are stable across re-renders
- Edge Cases and Integration
- should handle rapid form changes
- should handle simultaneous action item operations
- should maintain form state between multiple submit attempts
- should not interfere between submit and generate operations
- should ensure all action items have unique stable IDs
- Initial State
File: frontend/hooks/tests/useProgressStats.test.ts
- useProgressStats Hook
- Initialization
- should initialize with default state values
- should compute total time correctly
- should handle null analytics
- should return filteredActivity property
- MILESTONE_THRESHOLDS Constants
- should export MILESTONE_THRESHOLDS with correct values
- should use MILESTONE_THRESHOLDS values for milestone calculations
- State Updates
- Time Range
- should update time range to 30 days
- should update time range to 60 days
- should update time range to 90 days
- should handle multiple time range updates
- Chart Metric
- should update chart metric to lessons
- should update chart metric to time
- should toggle between metrics
- Time Range
- Total Time Computation
- should calculate hours and minutes correctly for 2 hours
- should calculate hours and minutes for 1h 30m
- should handle time less than 1 hour
- should handle zero seconds
- should handle large time values (10+ hours)
- should floor fractional minutes
- Milestone Computation
- 10 Lessons Milestone
- should achieve lesson milestone with exactly 10 lessons
- should achieve lesson milestone with more than 10 lessons
- should not achieve lesson milestone with less than 10 lessons
- should not achieve lesson milestone with zero lessons
- 7 Day Streak Milestone
- should achieve streak milestone with exactly 7 days
- should achieve streak milestone with more than 7 days
- should not achieve streak milestone with less than 7 days
- should not achieve streak milestone with zero streak
- Course Complete Milestone
- should achieve course milestone with exactly 1 course
- should achieve course milestone with more than 1 course
- should not achieve course milestone with zero courses
- Any Milestone Flag
- should set hasAnyMilestone to true when any milestone is achieved
- should set hasAnyMilestone to true when all milestones are achieved
- should set hasAnyMilestone to false when no milestones are achieved
- should handle combination of milestones (lesson + streak, no course)
- 10 Lessons Milestone
- Memoization
- should not recompute totalTime when unrelated state changes
- should not recompute milestones when unrelated state changes
- should recompute totalTime when analytics changes
- should recompute milestones when analytics changes
- Return Object Structure
- should return all expected properties
- should return functions for setters
- should return correct types for all values
- should have correct totalTime structure
- should have correct milestones structure
- Edge Cases
- should handle analytics update from null to defined
- should handle analytics update from defined to null
- should handle maximum time value
- should handle maximum lessons completed
- should handle maximum streak
- Filtered Activity
- should filter activity data to only include items within time range
- should filter activity based on 30 day time range
- should filter activity based on 60 day time range
- should filter activity based on 90 day time range
- should update filtered activity when time range changes
- should return empty array when analytics is null
- should return empty array when activity array is empty
- should clearly exclude activity older than time range
- should handle boundary dates based on time range setting
- should recompute filtered activity when time range changes
- should maintain correct activity data structure after filtering
- Initialization
File: frontend/hooks/tests/useUserEditForm.test.ts
- useUserEditForm Hook
- Initial State
- should initialize with loading state
- should have initial form data values
- Fetching User Data
- should fetch user data on mount
- should populate form data with user data
- should handle user with minimal data
- should handle fetch error
- should refetch user when userId changes
- should convert empty arrays to empty strings
- Form Data Changes
- should update form field when handleChange is called
- should update role field
- should update boolean field
- should clear success flag when field changes
- should clear error when field changes
- should update all editable fields
- Form Submission
- should submit form successfully
- should prevent default form submission
- should set saving state during submission
- should clear error and success before submission
- should convert comma-separated interests to array
- should convert comma-separated learning objectives to array
- should handle empty interests string
- should trim whitespace from array items
- should parse weekly learning hours as integer
- should handle empty weekly learning hours
- should submit all form fields with proper types
- should handle undefined/empty optional fields
- Error Handling
- should handle submission error with Error object
- should handle submission error with non-Error object
- should handle fetch error and set error message
- should handle submission error and set error message
- Edge Cases
- should handle userId being empty string
- should handle rapid successive field changes
- should handle commas in single interest item
- should handle multiple consecutive commas
- should reject zero as weekly learning hours with validation error
- should handle valid minimum weekly learning hours
- should handle user data with null values
- Initial State
File: frontend/lib/tests/logger.test.ts
- logger
- in development mode
- should log debug messages
- should log info messages
- should log warn messages
- should log error messages
- in production mode
- should NOT log debug messages in production
- should NOT log info messages in production
- should log warn messages in production
- should log error messages in production
- metadata handling
- should include metadata in log output
- should handle undefined metadata
- in development mode
File: frontend/lib/api/tests/admin-analytics.test.ts
- Admin Analytics API Client
- getAdminAnalytics
- Development Mode (Mock Data)
- should return mock data in development mode
- should simulate network delay
- should call getMockAdminAnalytics with correct range
- should default to 30d range when no range provided
- Production Mode (API Calls)
- should call API with correct endpoint and headers
- should include range in query parameters
- should include custom dates in query parameters
- should include compare parameter when requested
- should return parsed JSON response
- should fallback to mock data when API returns error status
- should fallback to mock data when API call throws error
- should handle missing session gracefully
- should handle session error gracefully
- Development Mode (Mock Data)
- exportAnalyticsCSV
- should return CSV blob in development mode
- should include overview metrics in CSV
- should include user metrics when requested
- should include course metrics when requested
- should include revenue metrics when requested
- should only include requested sections
- should handle multiple sections
- Production Mode
- should call export API endpoint
- should include sections in query parameters
- should throw error when API fails
- should return blob from API response
- downloadCSV
- should create download link and trigger download
- should set correct download filename
- should trigger link click
- should clean up after download
- formatValue
- Number Format
- should format small numbers without abbreviation
- should format thousands with K abbreviation
- should format millions with M abbreviation
- should use locale formatting for small numbers
- Currency Format
- should format small amounts in dollars and cents
- should format thousands with K abbreviation
- should format millions with M abbreviation
- should convert cents to dollars correctly
- Percent Format
- should format percentages with one decimal place
- should format zero percent correctly
- should format 100 percent correctly
- Duration Format
- should format minutes only for durations under 1 hour
- should format hours only for exact hours
- should format hours and minutes for mixed durations
- should format zero duration correctly
- String Values
- should return string values as-is
- should handle empty string
- Edge Cases
- should handle negative numbers
- should handle decimal numbers
- should handle very large numbers
- should default to number format for unknown format types
- Number Format
- getAdminAnalytics
File: frontend/lib/api/tests/ai-generation.test.ts
- AI Generation API Client
- startCourseGeneration
- should start course generation with basic input
- should start course generation with all optional fields
- should start synchronous course generation
- should start course generation with video generation enabled
- should handle different duration options
- should handle different difficulty levels
- should handle different tone options
- should handle validation errors
- should handle authorization errors
- should handle authentication errors
- getGenerationStatus
- should fetch generation job status
- should handle pending status
- should handle completed status
- should handle failed status with error message
- should handle different generation stages
- should handle 404 error for non-existent job
- should handle authentication errors
- regenerateLesson
- should regenerate lesson without additional context
- should regenerate lesson with additional context
- should handle 404 error for non-existent lesson
- should handle authorization errors
- should handle AI service errors
- cancelGeneration
- should cancel a generation job
- should handle successful cancellation
- should handle failed cancellation
- should handle 404 error for non-existent job
- should handle authorization errors
- getGenerationHistory
- should fetch generation history without parameters
- should fetch generation history with limit parameter
- should fetch generation history with offset parameter
- should fetch generation history with pagination parameters
- should return jobs array and total count
- should handle empty history
- should handle authentication errors
- should handle authorization errors
- Integration with apiClient
- should use the centralized apiClient for all operations
- PDF File Size Validation
- MAX_PDF_FILE_SIZE_BYTES constant
- should equal 5MB in bytes
- should equal 5242880 bytes
- should be a positive number
- isValidPdfFileSize
- should return true for files under 5MB
- should return true for files exactly at 5MB
- should return false for files over 5MB
- should return true for zero bytes
- should handle edge cases at boundary
- should handle decimal file sizes correctly
- should handle very large file sizes
- should handle negative file sizes
- Real-world file size scenarios
- should validate typical PDF file sizes
- should validate file sizes considering base64 overhead
- Integration with CourseGenerationInput
- should accept course generation with valid PDF size
- should detect invalid PDF size before API call
- MAX_PDF_FILE_SIZE_BYTES constant
- startCourseGeneration
File: frontend/lib/api/tests/analytics.test.ts
- Analytics API Client
- getUserAnalytics
- Production Mode
- should fetch user analytics with default days parameter
- should fetch user analytics with custom days parameter
- should fetch user analytics for 90 days
- should handle API errors in production mode
- should handle authentication errors
- Production Mode
- getActivityData
- should fetch activity data with default days parameter
- should fetch activity data with custom days parameter
- should return activity array from response
- should handle API errors
- getStreakData
- should fetch streak data
- should return streak object with correct properties
- should handle null last_activity_date
- should handle API errors
- formatDuration
- should format seconds only for very short durations
- should format minutes only for durations under 1 hour
- should format hours only for exact hours
- should format hours and minutes for mixed durations
- should handle large durations
- getTotalTime
- should return zero hours and minutes for zero seconds
- should return only minutes for durations under 1 hour
- should return exact hours with zero minutes
- should return hours and minutes for mixed durations
- should handle large durations
- should round down partial minutes
- Integration with apiClient
- should use the centralized apiClient for all operations
- getUserAnalytics
File: frontend/lib/api/tests/api-client.test.ts
- ApiClient
- ApiError
- should create an ApiError with message, status code and response
- should create an ApiError without response
- isAuthError
- should return true for 401 status code
- should return false for non-401 status codes
- isNotFound
- should return true for 404 status code
- should return false for non-404 status codes
- isValidationError
- should return true for 400 status code
- should return false for non-400 status codes
- ApiClient.request
- should add auth header when token is available
- should skip auth header when skipAuth is true
- should continue without auth if getIdToken returns null
- should continue without auth if getIdToken throws
- should include x-api-key header
- should include Content-Type header
- should handle 401 errors
- should handle 404 errors
- should handle network errors
- should handle non-Error exceptions
- should return empty object for 204 No Content
- should include response data in ApiError
- should handle malformed JSON response on error
- should stringify body when provided
- should not include body when not provided
- ApiClient.get
- should make GET request with query params
- should filter undefined params
- should filter null params
- should make GET request without query string when no params
- should make GET request without query string when all params are filtered
- ApiClient.post
- should make POST request with JSON body
- should make POST request without body
- ApiClient.put
- should make PUT request with JSON body
- should make PUT request without body
- ApiClient.patch
- should make PATCH request with JSON body
- should make PATCH request without body
- ApiClient.delete
- should make DELETE request
- should handle 204 No Content response
- ApiClient constructor
- should use custom baseUrl and apiKey
- apiClient singleton
- should export default apiClient instance
- should use environment variables for configuration
- Custom headers
- should allow custom headers to override defaults
- should merge custom headers with default headers
- Development logging
- should log auth token failures in development mode
- should not log auth token failures in production mode
- ApiErrorResponse interface
- should allow accessing error response fields with type safety
- should allow accessing additional error fields
- ApiError
File: frontend/lib/api/tests/categories.test.ts
- Categories API
- getCategories
- should fetch all categories successfully
- should handle empty categories list
- should throw ApiError when API returns error status
- should throw ApiError for 404 not found
- should throw ApiError for network errors
- should use centralized apiClient
- getCategory
- should fetch a single category by ID successfully
- should handle category not found
- should throw ApiError when API returns error status
- should pass category ID as query parameter
- should use centralized apiClient for single category
- Error Handling
- should throw ApiError for 401 unauthorized
- should throw ApiError for 403 forbidden
- should throw ApiError for 400 validation error
- should handle non-ApiError exceptions
- Type Exports
- should export CategoriesListResponse interface
- getCategories
File: frontend/lib/api/tests/courses.test.ts
- Courses API Client
- getCourses
- should fetch all courses without filters
- should fetch courses with category filter
- should fetch courses with search filter
- should fetch courses with duration filter
- should fetch courses with pagination parameters
- should fetch courses with all filters combined
- should handle API errors
- getCourse
- should fetch a single course by ID
- should handle 404 errors for non-existent course
- should handle authentication errors
- createCourse
- should create a new course
- should create a course with optional fields
- should handle validation errors
- should handle authorization errors for non-admin users
- updateCourse
- should update a course
- should update course status
- should update multiple course fields
- should handle 404 errors for non-existent course
- should handle authorization errors
- deleteCourse
- should delete a course
- should handle 404 errors for non-existent course
- should handle authorization errors
- should handle courses with active enrollments
- Integration with apiClient
- should use the centralized apiClient for all operations
- getCourses
File: frontend/lib/api/tests/enrollment-client.test.ts
- Enrollment API Client
- createEnrollment
- should create a new enrollment
- should create an enrollment with payment information
- should handle duplicate enrollment errors
- should handle course not found errors
- should handle authentication errors
- getUserEnrollments
- should fetch user enrollments with default pagination
- should fetch user enrollments with custom pagination
- should fetch enrollments with course details
- should handle no enrollments found
- should handle API errors
- getEnrollmentById
- should fetch a specific enrollment with progress
- should fetch completed enrollment
- should handle 404 errors for non-existent enrollment
- should handle authentication errors
- checkEnrollment
- should return enrolled status when user is enrolled
- should return not enrolled status when user is not enrolled
- should handle mock course IDs
- should handle network errors gracefully
- should handle API errors gracefully
- should handle non-Error exceptions gracefully
- updateEnrollmentStatus
- should mark enrollment as complete
- should mark enrollment as cancelled
- should handle 404 errors for non-existent enrollment
- should handle authorization errors
- should handle invalid status transition errors
- Integration with apiClient
- should use the centralized apiClient for all operations
- TypeScript type exports
- should export Enrollment interface
- should export EnrollmentWithCourse interface
- should export CreateEnrollmentData interface
- createEnrollment
File: frontend/lib/api/tests/lessons.test.ts
- Lessons API Client
- Backward Compatibility - Error Exports
- should export ApiError
- should export APIError (backward compatible alias)
- should have ApiError and APIError reference the same class
- should create ApiError instances correctly
- should create APIError instances correctly (backward compatible)
- should support error helper methods on both exports
- getLessons
- should fetch all lessons without filters
- should fetch lessons for a specific course
- should fetch lessons with pagination
- should fetch lessons with all filters combined
- should handle API errors
- getLesson
- should fetch a single lesson by ID
- should handle 404 errors for non-existent lesson
- should handle authentication errors
- createLesson
- should create a new lesson with required fields
- should create a lesson with all optional fields
- should handle validation errors
- should handle authorization errors for non-admin users
- updateLesson
- should update a lesson title
- should update lesson content
- should update multiple lesson fields
- should handle 404 errors for non-existent lesson
- should handle authorization errors
- deleteLesson
- should delete a lesson
- should handle 404 errors for non-existent lesson
- should handle authorization errors
- Integration with apiClient
- should use the centralized apiClient for all operations
- Error handling with both ApiError and APIError
- should catch errors thrown by apiClient using ApiError
- should catch errors thrown by apiClient using APIError (backward compatible)
- Backward Compatibility - Error Exports
File: frontend/lib/api/tests/progress.test.ts
- Progress API Client
- getProgress
- should fetch all progress without filters
- should fetch progress for a specific course
- should fetch progress for a specific lesson
- should fetch progress with lesson details
- should handle single progress response
- should handle empty progress response
- should handle API errors
- getLessonProgress
- should fetch progress for a specific lesson
- should return null when no progress exists
- should handle API errors
- getCourseProgress
- should fetch progress for all lessons in a course
- should fetch course progress with lesson details
- should handle empty course progress
- markLessonComplete
- should mark a lesson as complete
- should mark a lesson as complete with time spent
- should throw error when no progress data returned
- should handle API errors
- markLessonIncomplete
- should mark a lesson as incomplete
- should handle null response
- should handle API errors
- updateTimeSpent
- should update time spent on a lesson
- should throw error when no progress data returned
- should handle API errors
- getCourseProgressSummary
- should fetch course completion summary
- should handle course with no progress
- should handle completed course
- should handle API errors
- deleteCourseProgress
- should delete all progress for a course
- should handle 404 errors for non-existent course
- should handle authentication errors
- Integration with apiClient
- should use the centralized apiClient for all operations
- TypeScript type exports
- should export Progress interface
- should export ProgressWithLesson interface
- should export CourseProgressSummary interface
- getProgress
File: frontend/lib/api/tests/recommendations.test.ts
- Recommendations API Client
- getRecommendations
- Production Mode
- should fetch recommendations without parameters
- should fetch recommendations with type parameter
- should fetch recommendations with limit parameter
- should fetch similar course recommendations with courseId
- should fetch recommendations with all parameters
- should handle API errors in production mode
- should handle authentication errors
- Production Mode
- getPersonalizedRecommendations
- should fetch personalized recommendations with default limit
- should fetch personalized recommendations with custom limit
- should handle API errors
- getPopularCourses
- should fetch popular courses with default limit
- should fetch popular courses with custom limit
- should handle API errors
- getSimilarCourses
- should fetch similar courses with default limit
- should fetch similar courses with custom limit
- should handle API errors
- Integration with apiClient
- should use the centralized apiClient for all operations
- getRecommendations
File: frontend/lib/api/tests/types.test.ts
- API Types
- CourseStatus enum
- should define all valid course status values
- should only have three status values
- Category interface
- should accept a valid category object
- should accept optional fields
- Course interface
- should accept a valid course object with all required fields
- should only accept valid duration_days values (7, 14, or 21)
- should accept optional fields
- Lesson interface
- should include all required fields
- should include AI-related fields (migration 004_ai_generation)
- should allow AI-related fields to be optional
- should accept optional video_url and course_title fields
- should handle lessons array with AI-generated lessons
- CreateCourseDTO
- should accept valid course creation data
- should accept optional fields
- UpdateCourseDTO
- should make all fields optional
- should allow empty update object
- CreateLessonDTO
- should accept valid lesson creation data
- should accept optional fields
- UpdateLessonDTO
- should make all fields optional
- CoursesListResponse
- should structure courses list response correctly
- should handle empty courses list
- LessonsListResponse
- should structure lessons list response correctly
- should handle empty lessons list
- APIError
- should structure error response correctly
- should allow error without details
- Type compatibility with backend schema
- should match lessons table schema from migration 004_ai_generation
- should prevent TypeScript any type inference when mapping lessons
- Complex metadata and resources types
- should handle complex metadata objects
- should handle complex resources objects in lessons
- Edge cases and constraints
- should handle zero price courses
- should handle lessons with empty action_items
- should handle lessons with large estimated_duration_minutes
- CourseStatus enum
File: frontend/lib/auth/tests/auth-context.test.tsx
- AuthContext
- AuthProvider
- should load user on mount
- should handle user not authenticated on mount
- should set up token refresh interval
- useAuth hook
- should throw error when used outside AuthProvider
- should provide auth context values
- should correctly identify premium users
- signIn
- should sign in user and redirect to admin panel for admin users
- should sign in user and redirect to dashboard for regular users
- should handle sign in error
- signUp
- should sign up new user and redirect to dashboard
- should handle sign up error
- signOut
- should sign out user and redirect to signin page
- refreshUser
- should refresh user data
- withAuth HOC
- should render component for authenticated users
- should redirect unauthenticated users to signin
- should redirect non-admin users when requireAdmin is true
- should render for admin users when requireAdmin is true
- should redirect non-premium users when requirePremium is true
- should render for premium users when requirePremium is true
- should show loading state while checking auth
- should redirect to custom redirectTo path
- AuthProvider
File: frontend/lib/auth/tests/cognito-client.test.ts
- Cognito Client
- signUp
- should successfully sign up a new user
- should reject if sign up fails
- should reject if result is null
- signIn
- should successfully sign in a user
- should reject if authentication fails
- should reject if new password is required
- signOut
- should sign out the current user and clear storage
- should handle case when no user is logged in
- getCurrentSession
- should return current valid session
- should return null if no user is logged in
- should return null if session is invalid
- should return null on session error
- refreshSession
- should refresh the current session
- should return null if refresh fails
- getCurrentUser
- should return user info from session
- should return null if no session exists
- should use default values for missing fields
- getAccessToken
- should return access token
- should return null if no session
- getIdToken
- should return ID token
- confirmSignUp
- should confirm sign up with code
- should reject if confirmation fails
- resendConfirmationCode
- should resend confirmation code
- forgotPassword
- should initiate forgot password flow
- should reject on failure
- confirmPassword
- should confirm password reset
- changePassword
- should change password for authenticated user
- should reject if no user is logged in
- should reject on session error
- signUp
File: frontend/lib/auth/tests/cognito-config.test.ts
- Cognito Config
- COGNITO_CONFIG
- should contain configuration from environment variables
- getUserPool
- should return user pool when properly configured
- should return same instance on subsequent calls (singleton)
- requireUserPool
- should return user pool when properly configured
- should throw error when Cognito is not configured
- __resetUserPool
- should reset the singleton instance in test environment
- COGNITO_CONFIG
File: frontend/lib/auth/tests/redirect-utils.test.ts
- redirect-utils
- getPostAuthRedirect
- should redirect admin users to /admin
- should redirect premium users to /dashboard
- should redirect free users to /dashboard
- should redirect unknown roles to /dashboard
- should handle empty string role
- should handle case-sensitive role matching
- getPostAuthRedirect
File: frontend/lib/auth/tests/social-login.test.ts
- Social Login
- getSocialLoginUrl
- should generate correct Google OAuth URL
- should include state parameter for CSRF protection
- should generate correct Facebook OAuth URL
- should generate correct Apple OAuth URL
- should throw error if Cognito domain is not configured
- should throw error if client ID is not configured
- signInWithGoogle
- should redirect to Google OAuth URL
- signInWithFacebook
- should redirect to Facebook OAuth URL
- signInWithApple
- should redirect to Apple OAuth URL
- handleOAuthCallback
- should exchange authorization code for tokens and create session
- should throw error if state parameter is invalid (CSRF protection)
- should throw error if state parameter is missing
- should throw error if token exchange fails
- should throw error if ID token validation fails
- should throw error if Cognito is not configured
- should validate ID token issuer
- should validate ID token audience
- should reject expired tokens
- getSocialLoginUrl
File: tests/e2e/admin-panel.spec.ts
- should display admin panel for admin user
- should show admin badge/indicator
- should display welcome message with admin name
- should display all admin panel cards
- should display system health indicator
- should display recent activity section
- should have consistent branding with rest of app
- should redirect non-admin user from admin panel
- should redirect unauthenticated user from admin panel
- should navigate to courses management
- should navigate to lessons management
- should navigate to users management
- should navigate to analytics
- should navigate to AI content generation
- should navigate to settings
- should return to admin panel from header navigation
- should have responsive card grid layout
- should display icons for each admin card
- should show active status badges on cards
- should have consistent gradient backgrounds
- should display arrow icons on card hover
- should display header component
- should show sign out option
- should maintain admin session across navigation
File: tests/e2e/auth-admin.spec.ts
- should display sign-in page correctly
- should successfully sign in as admin user
- should redirect admin to admin panel after login
- should display admin panel cards
- should successfully sign out admin user
- should show error for invalid email
- should show error for invalid password
- should show error for empty fields
- should show loading state during sign-in
- should maintain session after page reload
- should allow sign-in from any page via navigation
- should prevent access to admin panel when not authenticated
- should remember me checkbox be present
File: tests/e2e/auth-user.spec.ts
- should successfully sign in as regular user
- should redirect user to dashboard after login
- should successfully sign out regular user
- should NOT show admin panel link for regular user
- should NOT allow regular user to access admin panel
- should show error for invalid credentials
- should maintain session after page reload
- should prevent access to dashboard when not authenticated
- should navigate to sign-up page from sign-in
- should display forgot password link
- should handle sign-in form validation
- should disable form during sign-in
- should clear error message on new input
File: tests/e2e/course-detail.spec.ts
- should display the back button in header
- should navigate back to courses page when clicking back button
- should display course title
- should display course description
- should display course rating
- should display student count
- should display course duration
- should display instructor information card
- should display course preview card with CTA
- should display tab navigation with Overview and Curriculum tabs
- should switch to Curriculum tab when clicked
- should switch back to Overview tab when clicked
- should highlight active tab
- should display
- should display
- should display Requirements section in Overview tab
- should display curriculum organized by weeks
- should display all 21 lessons in curriculum
- should display lesson duration in minutes
- should show lock icons for locked lessons
- should show available badge for unlocked lessons
- should display hover effects on lesson items
- should display CTA alert at bottom of curriculum
- should navigate to lesson detail when clicking an available lesson
- should be responsive on mobile viewport
- should be responsive on tablet viewport
- should display course statistics correctly
File: tests/e2e/courses.spec.ts
- should display the courses page title
- should display search input field
- should filter courses by search query
- should display filter toggle button
- should toggle filter panel when clicking filter button
- should display category filter buttons when panel is open
- should filter courses by category
- should display duration filter buttons when panel is open
- should filter courses by duration
- should apply combined filters (search + category + duration)
- should display course count
- should show empty state when no courses match filters
- should display course cards in grid layout
- should navigate to course detail page when clicking a course card
- should highlight active category filter
- should highlight active duration filter
- should reset filters to show all courses
- should be responsive on mobile viewport
- should be responsive on tablet viewport
File: tests/e2e/dashboard.spec.ts
- should display welcome section with user greeting
- should display user name in greeting
- should display current streak counter
- should display stats grid with 4 stat cards
- should display correct streak value in stats
- should display courses completed count
- should display total time spent
- should display active courses section
- should display 2 active courses from mock data
- should display course category badges
- should display course progress percentage
- should display progress bars for active courses
- should display
- should display lesson duration in
- should display
- should navigate to lesson when clicking
- should display
- should navigate to courses page when clicking
- should display recent achievements section
- should display achievement cards
- should display achievement dates
- should display
- should display goal checklist items
- should display daily progress bar
- should display motivation alert section
- should display upcoming lessons section in sidebar
- should display 3 upcoming lessons from mock data
- should display lesson time for upcoming lessons
- should display learning stats section
- should display weekly goal progress
- should display competitive insight
- should display user avatar
- should display fire icon for streak counter
- should have gradient effect on progress bars
- should be responsive on mobile viewport
- should be responsive on tablet viewport
- should display stats in grid layout
- should display course day progress (Day X of Y)
File: tests/e2e/enrollment.spec.ts
- should successfully enroll in a free course
- should not show CORS errors when making enrollment API calls
- should handle enrollment API errors gracefully
- should redirect to sign-in when trying to enroll without authentication
- should show enrolled state for already enrolled courses
- should navigate to lesson when re-clicking enrolled course
File: tests/e2e/home.spec.ts
- should display the header with navigation links
- should display auth buttons when user is not authenticated
- should display warm banner with promotional message
- should display hero section with primary CTA
- should navigate to courses page when clicking Explore Courses
- should display features section with feature cards
- should display popular courses preview section
- should navigate to course detail when clicking a course card
- should display footer with multiple sections
- should have responsive layout on mobile viewport
- should have responsive layout on tablet viewport
File: tests/e2e/lesson-detail.spec.ts
- should display lesson header with day indicator
- should display progress bar in header
- should display lesson title
- should display video player area
- should display lesson content
- should display action items section in sidebar
- should display action item checkboxes
- should toggle action item checkbox when clicked
- should update action items progress when checkbox is toggled
- should display action items progress bar
- should display
- should toggle lesson completion status when clicking
- should display completion badge when lesson is marked complete
- should update header progress bar when lesson is marked complete
- should display key takeaways section
- should display resources section
- should display resource links
- should display previous lesson navigation button
- should display next lesson navigation button
- should navigate to next lesson when clicking next button
- should navigate to previous lesson when clicking previous button
- should persist action item completion state
- should display video play button
- should display resource types (article, template, etc.)
- should be responsive on mobile viewport
- should be responsive on tablet viewport
- should have proper spacing in 3-column layout on desktop
File: tests/e2e/navigation.spec.ts
- should navigate from home to courses page
- should navigate from home to dashboard page
- should navigate to course detail from courses page
- should navigate back to courses from course detail
- should navigate to lesson from course curriculum
- should navigate between lessons using next button
- should navigate to lesson from dashboard continue learning button
- should navigate to courses from dashboard browse more button
- should navigate to home page by clicking logo
- should highlight active navigation link
- should maintain header across all pages
- should handle deep linking to specific lesson
- should handle deep linking to specific course
- should preserve scroll position when navigating back
- should handle browser forward navigation
- should display sticky header on scroll
- should show user avatar when authenticated
- should collapse navigation on mobile
- should handle non-existent course ID gracefully
- should handle non-existent lesson ID gracefully
File: tests/infrastructure/lambda-handler-config.test.ts
- Lambda Handler Configuration Validation
- Terraform Configuration Parsing
- should successfully parse lambda.tf file
- should find all expected Lambda functions
- should extract handler configuration for each Lambda
- Handler Path Format Validation
- should have valid handler format (module.function)
- should have handler paths that match the expected structure
- should not have the old incorrect handler format
- Zip File Structure Validation
- should have zip files that exist at the specified paths
- should have handler files that exist inside the zip archives
- should match handler module path to actual zip structure
- Handler Configuration Consistency
- should have consistent handler paths for similar functions
- should have zip paths that align with handler paths
- Specific Lambda Function Validations
- ${name}_handler
- should be defined in Terraform configuration
- should have the correct handler path
- should have the correct zip file path
- should have the handler file inside the zip
- ${name}_handler
- Regression Test: Original Bug Prevention
- should never have handler =
- should never have a handler path without directory structure
- should prevent mismatches between handler and zip contents
- Terraform Configuration Parsing
File: tests/workflows/change-detection.test.ts
- Change Detection Logic
- workflow_dispatch event
- should use input values when event is workflow_dispatch
- should default to true when inputs not provided
- push event - file change detection
- should detect infrastructure changes
- should detect backend changes
- should detect both infrastructure and backend changes
- should not detect changes in other directories
- should detect changes in nested infrastructure directories
- should detect changes in deeply nested backend function files
- should handle empty file list
- should be case-sensitive
- edge cases
- should not match partial directory names
- should match exact path prefixes
- should handle files with no extension
- should handle hidden files
- output format
- should format outputs correctly for GitHub Actions
- should use string boolean values
- conditional job execution
- should run build-lambdas when infrastructure changes
- should run build-lambdas when backend changes
- should skip deploy-infrastructure when no infrastructure changes
- should always run deployment-summary
- should run deploy-lambdas only when build succeeds
- should skip deploy-lambdas when build fails
- git diff simulation
- should parse git diff output correctly
- should handle empty git diff output
- should handle git diff with extra whitespace
- change count logic
- should count infrastructure changes correctly
- should return 0 for no changes
- should count backend changes correctly
- workflow_dispatch event
File: tests/workflows/claude-workflows.test.ts
- Claude Code Review Workflow
- workflow structure
- should have valid YAML syntax
- should have correct workflow name
- should trigger on pull_request events
- should filter by relevant paths
- permissions
- should have correct permissions for PR comments
- should not have excessive permissions
- job configuration
- should run on ubuntu-latest
- should checkout repository
- should use Claude Code action
- security - allowed tools
- should restrict Bash to specific gh commands
- should not allow wildcard Bash access
- should not allow dangerous commands
- prompt configuration
- should include PR context in prompt
- should reference CLAUDE.md for conventions
- should request specific review categories
- workflow structure
- Claude Auto-Fix Workflow
- workflow structure
- should have valid YAML syntax
- should have correct workflow name
- should trigger on issue label events
- should use concurrency control
- job conditions
- should only run when auto-fix label is added
- permissions
- should have write permissions for auto-fixing
- security - allowed tools
- should have specific allowed-tools configuration
- should allow specific command patterns only
- should not allow wildcard Bash access
- should use colon syntax for command patterns
- workflow steps
- should checkout with full history
- should log issue details
- should handle success case with label updates
- should handle failure case
- should trigger next issue in queue
- prompt configuration
- should include issue context
- should emphasize not guessing
- should reference interactive workflow
- workflow structure
- Claude Clarification Response Workflow
- workflow structure
- should have valid YAML syntax
- should have correct workflow name
- should trigger on issue comments
- should use per-issue concurrency control
- job conditions
- should only run on clarification responses
- should avoid bot comment loops
- permissions
- should have write permissions for continuing fix
- security - allowed tools
- should have specific allowed-tools configuration
- should allow same tools as auto-fix
- should not allow wildcard Bash access
- workflow steps
- should acknowledge user response
- should update labels during processing
- should mark fix attempted on success
- prompt configuration
- should include clarification context
- should instruct to fetch all comments
- should limit clarification rounds
- workflow structure
- Claude General Workflow
- workflow structure
- should have valid YAML syntax
- should have correct workflow name
- should trigger on multiple events
- job conditions
- should only run when @claude is mentioned
- should handle different event types
- permissions
- should have comprehensive write permissions
- should explicitly specify actions read permission
- security - allowed tools
- should have explicit allowed-tools configuration
- should allow comprehensive toolset
- should not allow wildcard Bash access
- should use proper command pattern syntax
- workflow steps
- should checkout with minimal depth
- should use Claude Code action
- workflow structure
- Cross-workflow Security Validation
- allowed-tools consistency
- should all use specific command patterns
- should not allow dangerous commands in any workflow
- permission validation
- should only grant write permissions when necessary
- should require pull-requests write for PR operations
- secret handling
- should use CLAUDE_CODE_OAUTH_TOKEN from secrets
- should use GITHUB_TOKEN from secrets for gh commands
- allowed-tools consistency
- Workflow Best Practices
- action versions
- should use pinned action versions
- error handling
- should have failure handling steps where appropriate
- concurrency control
- should use concurrency for sequential workflows
- runner configuration
- should use ubuntu-latest for all jobs
- action versions
File: tests/workflows/deploy-infrastructure.test.ts
- Deploy Infrastructure Workflow
- Workflow Structure
- should have valid YAML syntax
- should have a descriptive name
- should have correct permissions
- should define required environment variables
- Workflow Triggers
- should trigger on push to main branch
- should trigger on infrastructure changes
- should trigger on backend function changes
- should trigger on workflow file changes
- should support manual workflow dispatch
- should have workflow_dispatch inputs for deployment control
- Job: detect-changes
- should exist and run on ubuntu-latest
- should have correct outputs
- should checkout code with fetch-depth 2
- should have detect changes step with correct logic
- should print detected changes
- Job: build-lambdas
- should depend on detect-changes job
- should only run when changes detected
- should setup Node.js with correct version
- should build all Lambda functions
- should upload Lambda artifacts
- should include all Lambda zip paths in upload
- Job: deploy-infrastructure
- should depend on both detect-changes and build-lambdas
- should only run when infrastructure changes detected
- should not specify GitHub environment during MVP phase
- should have working directory set to terraform
- should have correct Terraform outputs
- should download Lambda artifacts
- should configure AWS credentials
- should setup Terraform with correct version
- should run terraform init
- should run terraform validate
- should run terraform plan with all OAuth secrets
- should run terraform apply with auto-approve
- should get terraform outputs
- Job: deploy-lambdas
- should depend on detect-changes, build-lambdas, and deploy-infrastructure
- should run when build succeeds and changes detected
- should not specify GitHub environment during MVP phase
- should deploy all Lambda functions
- should use correct Lambda function names
- should wait for Lambda updates to complete
- Job: deployment-summary
- should depend on detect-changes, deploy-infrastructure, and deploy-lambdas
- should always run regardless of previous job results
- should generate deployment summary
- should check for failures and exit with error code
- Job Dependencies and Orchestration
- should have correct job execution order
- should skip unnecessary jobs based on changes
- Security and Best Practices
- should use pinned action versions
- should use secrets for sensitive data
- should not use GitHub environment protection during MVP phase
- should have minimal permissions
- Error Handling and Resilience
- should handle missing Terraform outputs gracefully
- should handle missing AI Lambda zips gracefully
-
should use true for non-critical failures - should have deployment summary that always runs
- Lambda Function Coverage
- should build all Lambda functions
- should deploy all Lambda functions
- Workflow Structure
File: tests/workflows/lambda-deployment.test.ts
- Lambda Deployment Configuration
- Lambda Function Inventory
- should define all regular Lambda functions
- should define all AI generation handlers
- should have unique function names
- Lambda Build Paths
- should have correct source paths for regular functions
- should have correct source paths for AI generation handlers
- should have correct dist paths for regular functions
- should have correct dist paths for AI generation handlers
- should have package.json in each function directory
- Lambda Function Names
- should generate correct function names for regular functions
- should generate correct function names for AI handlers
- should follow naming convention pattern
- should use environment suffix consistently
- AWS Lambda Update Command
- should generate correct AWS CLI command for courses function
- should generate correct AWS CLI command for AI handlers
- should use fileb:// prefix for binary file upload
- should support different AWS regions
- Lambda Wait Command
- should generate correct wait command
- should support all regular functions
- AI Generation Handler Deployment Loop
- should deploy all AI handlers
- should use consistent naming for AI handlers
- should map handlers to correct zip files
- should handle missing zip files gracefully
- Build Process Validation
- should use npm ci for reproducible builds
- should use npm run build for all functions
- should execute commands in correct order
- Artifact Upload/Download
- should have correct artifact name
- should include all Lambda function zip files
- should have short retention period for CI artifacts
- should use glob pattern for AI generation zips
- Deployment Error Handling
- should continue on AI handler deployment warnings
- should skip missing zip files
-
should use true for non-critical lambda wait failures
- Node.js and NPM Cache Configuration
- should use npm for caching
- should cache all function package-lock.json files
- should include package-lock.json for all Lambda functions
- Lambda Function Inventory
File: tests/workflows/sync-docs-script.test.ts
- Sync Docs Script
- script existence and permissions
- should exist
- should be executable
- should have bash shebang
- script structure
- should use set -euo pipefail for safety
- should have logging functions
- should have validation function
- should have main sync functions
- should have main execution function
- text replacement logic
- should replace Claude models with Gemini models
- should replace model identifiers
- should replace file tree references
- should replace generated with attribution
- should remove co-authored-by lines
- should replace automated analysis attribution
- should replace automated fix attribution
- should replace clarifying questions reference
- should replace file references
- should replace Claude.md filename
- should handle multiple replacements in same text
- should not replace partial matches
- should be case-sensitive for most replacements
- validation logic
- should validate when all source files exist
- should fail when Claude.md is missing
- should fail when .claude/commands is missing
- should fail when both are missing
- should provide descriptive error messages
- file operations
- should sync Claude.md to Gemini.md
- should sync command files to prompts directory
- should preserve filenames when syncing prompts
- should create target directory if not exists
- error handling
- should exit on validation failure
- should report file creation failure
- should continue with zero prompt files
- output messages
- should log start message
- should log validation success
- should log completion message
- should use colored output for visibility
- command file processing
- should replace Claude with Gemini in command files
- should replace lowercase claude with gemini
- should handle mixed case
- should preserve file structure
- directory structure
- should expect Claude.md in repository root
- should expect .claude/commands directory
- should create gemini/prompts directory
- should use mkdir -p for directory creation
- execution context
- should be run from repository root
- should validate current directory
- integration with workflow
- should be called from workflow
- should run after branch setup
- should run before commit step
- edge cases
- should handle empty Claude.md
- should handle no command files
- should handle very long lines
- should handle special characters
- should handle unicode characters
- should handle multiple consecutive spaces
- performance considerations
- should process files sequentially
- should count processed files
- should report file count
- script existence and permissions
File: tests/workflows/sync-docs.test.ts
- Sync Docs Workflow
- YAML syntax validation
- should have valid YAML syntax
- should have required workflow structure
- should have correct concurrency configuration
- should have required permissions
- should have workflow_dispatch trigger
- should have schedule trigger
- branch detection logic
- should detect remote branch exists
- should detect remote branch does not exist
- should handle empty remote branches list
- should match exact branch name only
- local branch detection logic
- should detect local branch exists
- should detect local branch does not exist
- branch management scenarios
- Scenario 1: Remote branch does not exist (fresh start)
- should create fresh branch from main
- should not perform reset when creating fresh branch
- Scenario 2: Remote branch exists and is behind main
- should checkout remote branch and reset to main
- should reset to main to synchronize state
- Scenario 3: Remote branch exists and is ahead of main
- should still reset to main (automated branch)
- should create local tracking branch if not exists
- Scenario 4: Local branch exists but remote does not
- should create fresh branch (ignoring stale local)
- Scenario 1: Remote branch does not exist (fresh start)
- git push logic
- should use force-with-lease when remote branch exists
- should use normal push when creating new remote branch
- should always set upstream
- push command generation
- should generate correct push command for existing remote branch
- should generate correct push command for new remote branch
- should never use plain –force
- change detection logic
- should detect changes when files are staged
- should detect no changes when staging area is empty
- should commit when changes exist
- should skip commit when no changes exist
- PR creation logic
- should create PR when branches differ
- should skip PR when branches are identical
- should skip PR when branch is behind main
- workflow step sequence
- should execute steps in correct order
- should fetch all history in checkout step
- should configure git user before making commits
- concurrency handling
- should use fixed concurrency group
- should cancel in-progress runs
- should prevent concurrent runs on same branch
- error scenarios
- git operations
- should handle fetch failures gracefully
- should handle checkout failures
- push failures
- should succeed with force-with-lease after reset
- should fail if someone else pushed in between
- should fail on network issues
- git operations
- commit message format
- should use conventional commit format
- should be descriptive
- PR creation details
- should have descriptive PR title
- should have informative PR body
- should target main branch
- should use chore/doc-sync branch as head
- should handle PR already exists scenario
- security considerations
- should use GITHUB_TOKEN for authentication
- should not expose secrets in logs
- should have minimal required permissions
- edge cases
- should handle empty sync results
- should handle very large file changes
- should handle special characters in commit messages
- should handle branch names with special characters
- schedule configuration
- should run daily
- should use UTC time
- YAML syntax validation