fetch() calls, enabling fully offline testing of your MCP server.
Why HTTP Mocking?
Consider a tool that fetches weather data:- Tests fail offline
- Tests depend on external API availability
- Tests may hit rate limits
- Tests are slow due to network latency
- Tests can’t simulate error conditions
Basic Usage
URL Matching
Exact URL Match
Partial URL Match
URLs are matched if they contain the specified string:Regular Expression
Custom Matcher Function
HTTP Methods
Convenience Methods
Full Mock Definition
Request Matching
Match by Headers
Match by Request Body
Response Helpers
httpResponse Utilities
Full Response Object
One-Time Mocks
Create mocks that only match a limited number of times:Call Tracking
Track Mock Usage
Wait for Calls
Passthrough Mode
Allow unmatched requests to reach the real network:Verification
Assert All Mocks Used
Check Pending Mocks
Scope and limits
httpMockpatchesfetchin the test process. It sees calls made by code that runs in the same process (for example a server started withTestServerin-process or a direct client), not calls made by a separate server process started bytest.use({ server }).- Only
fetchis intercepted, nothttp.requestor libraries that bypassfetch. - The helpers (
get,post,put,delete,any) accept an optional third argument{ times, name, match }.matchadds header, body or method constraints on top of the URL. - Requests made with a
Requestobject are matched the same way as URL strings.
Cleanup
Pattern: Using try/finally
Pattern: beforeEach/afterEach
Global Disable
Real-World Examples
Testing OpenAPI Adapter
Testing Error Handling
Testing Rate Limiting
Best Practices
Do:- Always call
restore()in cleanup (it puts the originalfetchback) - Use
httpResponsehelpers for common responses - Verify mocks were used with
assertDone() - Mock at the appropriate level of detail
- Forget cleanup (breaks other tests)
- Enable passthrough without good reason
- Over-mock (test real HTTP handling sometimes)
- Hard-code response data that should be dynamic