Skip to content

Conversation

mcollina
Copy link
Member

@mcollina mcollina commented Aug 2, 2025

Summary

This PR implements comprehensive debugging improvements for MockAgent to address the common pain point of difficult debugging when mocks don't match requests. The changes provide detailed context, intelligent suggestions, and powerful state inspection tools.

🚀 Key Features

Enhanced Error Messages

  • Rich context: MockNotMatchedError now includes available interceptors table, request details, and potential matches
  • Smart suggestions: Similarity-based matching recommendations when requests fail
  • Actionable feedback: Clear indication of why requests don't match specific interceptors

Real-time Request Tracing

  • Basic mode (traceRequests: true): Simple match/no-match with interceptor suggestions
  • Verbose mode (traceRequests: 'verbose'): Detailed step-by-step matching process
  • Console output: All tracing goes to console.error for easy debugging

Development Mode

  • Auto-configuration: developmentMode: true automatically enables debugging features
  • Zero-config debugging: Call history, tracing, and verbose errors enabled by default

State Inspection Tools

  • debug(): Returns comprehensive MockAgent state as structured data
  • inspect(): Pretty-prints debug information to console with tables
  • compareRequest(): Detailed diff analysis between requests and interceptors

Interceptor Validation

  • validate(): Proactive validation of interceptor configuration
  • Issue detection: Identifies common problems like double slashes, unusual methods, conflicting settings
  • Severity levels: Distinguishes between warnings and errors

Enhanced Assertions

  • Extended assertNoPendingInterceptors() with new options:
    • showUnusedInterceptors: Display interceptors that were never called
    • showCallHistory: Include recent request history in error messages
    • includeRequestDiff: Show detailed comparison between recent requests and pending interceptors

📊 Usage Examples

// Development mode - auto-enables all debugging features
const mockAgent = new MockAgent({ developmentMode: true })

// Real-time request tracing
const mockAgent = new MockAgent({ traceRequests: 'verbose' })

// State inspection
mockAgent.inspect() // Pretty console output
const state = mockAgent.debug() // Structured data

// Interceptor validation
const scope = mockPool.intercept({ path: '/api', method: 'GET' }).reply(200, {})
const validation = scope.validate()

// Request analysis
const diff = mockAgent.compareRequest(request, interceptor)

// Enhanced error reporting
mockAgent.assertNoPendingInterceptors({
  showUnusedInterceptors: true,
  showCallHistory: true,
  includeRequestDiff: true
})

🔧 Technical Details

  • Backward compatible: All changes are opt-in and don't affect existing functionality
  • TypeScript support: Complete type definitions for all new methods and options
  • Performance: Debugging features only activate when explicitly enabled
  • Testing: Comprehensive test suite with 11 test cases covering all features
  • Code quality: Passes all linting checks and follows existing patterns

📈 Before/After

Before:

MockNotMatchedError: Mock dispatch not matched for path '/api/users'

After:

Mock dispatch not matched for path '/api/users'

Available interceptors for origin 'http://localhost:3000':
┌─────────┬────────┬─────────────┬─────────────┬────────────┐
│ Method  │ Path   │ Status      │ Persistent  │ Remaining  │
├─────────┼────────┼─────────────┼─────────────┼────────────┤
│ GET     │ /api/  │ 200         │ ❌          │ 1          │
│ POST    │ /users │ 201         │ ✅          │ ∞          │
└─────────┴────────┴─────────────┴─────────────┴────────────┘

Request details:
- Method: GET
- Path: /api/users
- Headers: {"content-type": "application/json"}
- Body: undefined

Potential matches:
- GET /api (path mismatch, similarity: 0.7)
- POST /users (method mismatch)

🧪 Test Plan

  • All existing MockAgent tests continue to pass
  • New debugging features work in isolation
  • Development mode enables features correctly
  • Request tracing outputs expected console messages
  • Enhanced error messages include proper context
  • Interceptor validation detects common issues
  • TypeScript definitions are complete and accurate
  • Performance impact is minimal when features disabled

🔗 Related

Addresses the MockAgent debugging challenges outlined in the planning document. This implementation follows the prioritized feature list and maintains full backward compatibility while dramatically improving the debugging experience.

🤖 Generated with Claude Code

mcollina and others added 8 commits August 2, 2025 11:34
Add comprehensive plan to improve MockAgent debugging experience
including enhanced error messages, real-time request tracing,
and development mode features.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Matteo Collina <[email protected]>
Add comprehensive debugging features to MockAgent:

- Enhanced error messages with interceptor context and suggestions
- Real-time request tracing with console.error output
- MockAgent.debug() method for state inspection
- MockAgent.inspect() method for formatted console output
- New constructor options: traceRequests, developmentMode, verboseErrors
- Development mode that auto-enables debugging features
- Smart request matching with similarity scoring
- Updated TypeScript definitions
- Comprehensive test coverage

Features improve debugging experience by providing detailed context
when mocks don't match, real-time request visibility, and easy
state inspection tools.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Matteo Collina <[email protected]>
Add MockAgent.compareRequest() method that compares a request
against an interceptor and returns detailed difference analysis:

- Field-by-field comparison (path, method, body, headers)
- Similarity scoring for each field
- Overall match score calculation
- Detailed difference objects with expected vs actual values

This helps developers understand exactly why a request doesn't
match a specific interceptor, making debugging more precise.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Matteo Collina <[email protected]>
Add comprehensive debugging features to complete the plan:

**Interceptor Validation:**
- Add MockScope.validate() method for interceptor configuration validation
- Detect common issues like double slashes, unusual methods, conflicting settings
- Provide detailed feedback with severity levels (warning/error)

**Enhanced assertNoPendingInterceptors:**
- Add showUnusedInterceptors option to show interceptors never called
- Add showCallHistory option to include recent call history in errors
- Add includeRequestDiff option for detailed request vs interceptor comparison

**Smart Request Tracing:**
- Enhanced tracing with closest match suggestions in basic mode
- Show available interceptors when requests don't match
- Intelligent similarity-based recommendations

**Utility Functions:**
- Export calculateStringSimilarity, findClosestMatches, buildEnhancedErrorMessage
- Complete TypeScript definitions for all new methods and options
- Comprehensive test coverage for all features

All features maintain backward compatibility and follow existing code patterns.
The implementation significantly improves MockAgent debugging experience with
actionable insights when mocks don't work as expected.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Matteo Collina <[email protected]>
… coverage

- Add configurable console option to MockAgent for custom tracing output
- Implement comprehensive test suite for all tracing scenarios (basic, verbose, custom console)
- Fix enhanced error messages to be opt-in via verboseErrors option to maintain backward compatibility
- Update TypeScript definitions to include console option
- Add example demonstrating custom console usage for tracing
- Ensure all 92 existing MockAgent tests continue to pass

The console option allows developers to:
- Capture tracing output in tests for assertions
- Send logs to custom logging systems
- Filter or format tracing messages
- Test tracing behavior itself

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Matteo Collina <[email protected]>
- Fix assertNoPendingInterceptors signature to include new options
- Add type tests for debug(), inspect(), and compareRequest() methods
- Add type tests for new constructor options (traceRequests, developmentMode, verboseErrors, console)
- Add type tests for MockScope.validate() method
- Ensure all TypeScript tests pass with proper type coverage

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Matteo Collina <[email protected]>
Signed-off-by: Matteo Collina <[email protected]>
Add detailed documentation for the new MockAgent debugging capabilities:

- New constructor options: traceRequests, developmentMode, verboseErrors, console
- Request tracing with basic and verbose modes
- Enhanced error messages with interceptor context
- debug() and inspect() methods for state inspection
- compareRequest() method for interceptor analysis
- Enhanced assertNoPendingInterceptors() options
- Custom console support for testing
- Development mode for streamlined debugging setup

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
Signed-off-by: Matteo Collina <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant