Overview
Express Zod API provides specialized testing utilities that make it easy to test your endpoints and middlewares without running a full server. The framework usesnode-mocks-http internally to mock request and response objects.
Testing Endpoints
Use thetestEndpoint() function to test your endpoints:
Testing Middlewares
Test middlewares individually usingtestMiddleware():
Complete Testing Examples
Testing a Simple GET Endpoint
Testing POST with Validation Errors
Testing Authentication Middleware
Testing with Context
Testing Options
requestProps
Additional properties to set on the Request mock:responseOptions
Options for the Response mock (see node-mocks-http):configProps
Additional configuration properties:loggerProps
Additional logger properties:Logger Mock Methods
The logger mock provides a special_getLogs() method:
Example
Response Mock Methods
The response mock provides these assertion helpers:Testing File Uploads
Testing Custom Result Handlers
Best Practices
Test Both Success and Error Cases
Test Both Success and Error Cases
Always test both successful responses and error conditions to ensure your error handling works correctly.
Check Logger Output
Check Logger Output
Verify that no unexpected errors were logged using
loggerMock._getLogs().error.Test Middleware Chains
Test Middleware Chains
Test middlewares individually and then test endpoints with middlewares attached to ensure proper context passing.
Use Snapshots for Complex Responses
Use Snapshots for Complex Responses
For complex response structures, consider using snapshot testing to detect unexpected changes.
Mock External Dependencies
Mock External Dependencies
Mock database calls and external services to keep tests fast and isolated.
Integration Testing
For full integration tests, start the actual server:Related Topics
- Middlewares - Creating and using middlewares
- Endpoints - Building endpoints
- Error Handling - Handling errors