Starter Templates
Jumpstart your API gateway development process with our pre-built starter templates
Mocking & Unit Test
Create unit tests by mocking Zuplo objects.
npx create-zuplo-api --example test-mocksMocking & Unit Testing
This example demonstrates how to write unit tests for Zuplo handlers by mocking ZuploRequest and ZuploContext. The sample uses Mocha and Sinon for testing and mocking, but the concepts apply to any test framework.
Prerequisites
- A Zuplo account. You can sign up for free.
- Node.js installed locally for running tests
Working with this Example
Locally
Working locally is the best way to explore and understand the code for this example. You can get a local version by using the Zuplo CLI:
Then, in the project directory run the following commands:
Running the Tests
To run the unit tests:
Deploy this example to Zuplo
It is also possible to deploy this example directly to your Zuplo account and work with it via the Zuplo Portal. You can do this by clicking the Deploy to Zuplo button anywhere on this page.
How It Works
Mocking ZuploRequest
Since ZuploRequest extends the standard Request class, you can create a mock by extending Request and adding the Zuplo-specific properties:
Mocking ZuploContext
Create a mock context object with the properties your handlers use:
Testing Handlers
With the mocks in place, you can test handlers directly:
Mocking External API Calls
Use undici's MockAgent to mock fetch calls your handlers make:
Project Structure
Test Examples
Testing a Simple Handler
Testing with Path Parameters
Using Sinon Spies
Common Customizations
- Add more mock properties: Extend the mock context with
request.user,context.custom, etc. - Test policies: Apply the same mocking approach to test custom policies
- Test error cases: Verify handlers return appropriate error responses
- Integration tests: Use Zuplo's test framework for end-to-end testing
Learn More
Other Examples
Jumpstart your API gateway development process with our pre-built starter templates