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
ZuploRequest can be constructed directly — import it from @zuplo/runtime and pass params (and any other request init options) straight to the constructor. There’s no need to hand-roll a subclass:
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. Node’s built-in fetch is its own bundled copy of undici, so setGlobalDispatcher alone won’t reach it — also point globalThis.fetch at undici’s own fetch so the mocked dispatcher is actually used:
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