Webhook Tests in CI
Webhook handlers break in ways unit tests miss: a provider adds a field, a transform changes a payload's shape, or a refactor stops the handler from verifying signatures. Webhook tests catch these in a pull request by sending real webhook requests to your app before the change ships.
It works in two steps, both in the Hookbase CLI (2.18.0 or later):
hookbase fixtures pullasks Hookbase for the requests a destination received, with personal data replaced by realistic fakes, and writes each one to a JSON file. You review the files and commit them.hookbase test runsends each fixture straight from the CI runner to your app, signed like a Hookbase delivery, and checks the responses against rules you write inhookbase.tests.yaml. It needs no API key and makes no request to Hookbase.
The fixtures are the requests your app actually gets: after the route's transform, with the destination's path, method and content type.
Events and Catalog Fixtures
fixtures pull has two modes:
Events (--mode events, the default) | Catalog (--mode catalog) | |
|---|---|---|
| What it pulls | Recent deliveries to the destination: delivered ones, plus failed ones with --include-failed | The provider's sample payloads, for each route to the destination, run through the route's transform, filter and JSON Schema |
| Plans | Pro and Business | Every plan |
| Permissions | destinations:read and events:export | destinations:read |
A read-only API key can pull in both modes. Catalog mode uses the source's provider. For a source with
no provider set, pass one with --provider stripe (any provider id from the
integrations catalog). Samples a route's filter drops or its schema rejects are
skipped, as a live event would be.
By default, events mode takes the newest delivery of each event type on each route, up to 20 fixtures.
Narrow it with --event-type 'invoice.*', --route <id> or --event-id <id>, and raise it with
--per-type (up to 5) and --limit (up to 50). Fixtures can only be pulled for HTTP destinations.
Set Up
1. Write the config and a test secret
Run this in your app's repository, with the destination your app receives from:
hookbase test init -d my-api --target http://localhost:3000It writes hookbase.tests.yaml and prints a new test signing secret (whsec_…) once. Save it as a
CI secret named HOOKBASE_TEST_SIGNING_SECRET.
2. Make your app verify with the test secret in CI
test run signs each fixture with the test secret, using the same
Standard Webhooks headers as a real delivery
(webhook-id, webhook-timestamp, webhook-signature and the x-hookbase-* aliases). Your app keeps
its normal verification code. In CI, give it the test secret where it would read the destination's
secret:
# Production: the destination's real secret
HOOKBASE_DESTINATION_SECRET=whsec_from_the_dashboard
# CI and local test runs: the test secret from hookbase test init
HOOKBASE_DESTINATION_SECRET=$HOOKBASE_TEST_SIGNING_SECRETWarning
Never use the destination's real signing secret in CI, and never let production accept the test secret. Anyone with the test secret can sign requests your app trusts.
Signing this way also tests your verification: a handler that rejects a valid signature fails the
run. If your app doesn't verify signatures, set signing: none in the config or pass --no-sign.
3. Pull, review and commit fixtures
hookbase fixtures pullWithout -d, it pulls the destinations listed under pull.destinations in the config. Files go to
.hookbase/fixtures/<destination>/<source>/<event type>--<event id>.json, and each one follows the
fixture schema. For each file, the CLI prints what was scrubbed:
My API (my-api)
+ .hookbase/fixtures/my-api/stripe/payment_intent.succeeded--7f9c2b1e.json added
scrubbed: $.data.object.receipt_email (email, builtin), $.data.object.shipping.name (name, builtin)
! Free text was not checked for names: $.data.object.descriptionRead the files, and especially any warnings, before you commit them (see
What the scrubber does). Then commit .hookbase/fixtures and
hookbase.tests.yaml.
4. Run the tests
Start your app, then:
export HOOKBASE_TEST_SIGNING_SECRET=whsec_...
hookbase test runWebhook tests 3 fixtures → http://localhost:3000
✓ my-api/stripe/payment_intent.succeeded--7f9c2b1e.json 200 41 ms
✓ my-api/stripe/invoice.paid--0c41d9aa.json 200 18 ms
✗ my-api/stripe/customer.subscription.deleted--5b2e7d10.json 500 12 ms
status 500, expected 2xx
response: {"error":"Cannot read properties of undefined (reading 'items')"}
2 passed, 1 failed (3 fixtures, 0.1 s)The Config File
hookbase test run reads hookbase.tests.yaml (or .yml, or .json) from the current directory, or
the file you pass with --config. Here is the file test init writes, with its commented examples
filled in:
version: 1
target: ${WEBHOOK_TEST_TARGET:-http://localhost:3000}
fixtures: .hookbase/fixtures
signing:
secretEnv: HOOKBASE_TEST_SIGNING_SECRET
# fresh: new delivery and event ids on every send. stable: the same ids every run.
ids: fresh
# Values for headers the destination sends but fixtures leave out (see omittedHeaders)
headers:
Authorization: "Bearer ${WEBHOOK_TEST_TOKEN}"
timeoutMs: 30000
concurrency: 1
waitFor:
url: http://localhost:3000/health
timeoutMs: 60000
pull:
destinations: [my-api]
mode: events
perType: 1
limit: 20
keep: ["$.order.items[*].name"] # product names, not people
defaults:
expect:
status: 2xx
tests:
- match: { eventType: "payment_intent.*" }
expect:
status: 200
maxLatencyMs: 2000
headers:
content-type: { matches: "^application/json" }
body:
- { path: "$.received", equals: true }
- { path: "$.error", exists: false }
- match: { eventType: ["invoice.paid", "invoice.payment_failed"] }
expect:
expr: 'body.status in ["processed", "ignored"]'
schema: schemas/webhook-ack.json
- match: { file: "**/customer.subscription.deleted--*" }
skip: "not handled yet"${VAR} and ${VAR:-default} read environment variables, and $${ writes a literal ${. A variable
that isn't set and has no default is an error. The config can't read Hookbase or CI credentials (see
Security).
Assertions
Every fixture gets defaults.expect, then the expect of each tests entry that matches it, in order.
A later entry replaces status, maxLatencyMs, expr and schema, adds to headers, and appends
to body. A fixture with no rules must answer with a 2xx status.
| Rule | Passes when |
|---|---|
status | The status matches: a number (200), a class (2xx), or a list of either ([200, 202]) |
maxLatencyMs | The response arrived within this many milliseconds |
headers | Each named response header matches. A string must be equal; or use { equals: … }, { matches: "regex" } or { exists: false }. Names are case-insensitive |
body | Each { path, … } entry holds for the JSON response body: equals a value, matches a regex, or exists: true / false. Paths look like $.a.b, $.items[0] or $["dotted.key"] |
expr | A JSONata expression over status, headers, body, latencyMs and fixture is truthy |
schema | The response body validates against this JSON Schema file, relative to the config |
Regexes are written "pattern" or "/pattern/flags". A tests entry matches by eventType (a glob
where * matches anything, or a list) and by file (a path glob under the fixtures directory, where
** crosses directories). An entry can also set path to send the fixture to a different path, and
skip (true or a reason) to report it as skipped.
Ids
Each send carries X-Delivery-ID and X-Event-ID, and webhook-id is the delivery id. With
ids: fresh, the default, every run uses new ids, so deduplication in your app doesn't drop a fixture
it saw on the previous run. With ids: stable, ids are the same on every run (the event id is the
fixture's own), which lets you test that your app handles a redelivery only once.
Running in GitHub Actions
Run the tests on pull_request, against the committed fixtures:
name: Webhook tests
on:
pull_request:
permissions:
contents: read
jobs:
webhook-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm ci
- name: Start the app
run: npm start &
env:
# The app verifies webhooks with the test secret here
HOOKBASE_DESTINATION_SECRET: ${{ secrets.HOOKBASE_TEST_SIGNING_SECRET }}
- name: Webhook tests
run: npx --yes @hookbase/cli@2 test run --wait-for http://localhost:3000 --junit webhook-tests.xml
env:
HOOKBASE_TEST_SIGNING_SECRET: ${{ secrets.HOOKBASE_TEST_SIGNING_SECRET }}
- uses: actions/upload-artifact@v4
if: always()
with:
name: webhook-tests
path: webhook-tests.xml--wait-for polls the URL until it answers with a status below 500 (for up to 60 seconds), so the tests
don't start before the app is listening. @hookbase/cli@2 stays on the current major version. The CLI
needs Node.js 20.12 or later.
In GitHub Actions, test run also writes a table of results to the job summary and adds an error
annotation for each failed fixture (the first 10). --junit writes a JUnit XML report, with one test suite per
destination and one test case per fixture, for test reporters in GitHub, GitLab and other CI systems.
--json prints the results as JSON instead.
Info
Pull requests from forks don't get repository secrets, so HOOKBASE_TEST_SIGNING_SECRET is empty there
and test run exits with code 2. If fork pull requests must run the tests, you can commit a test secret
in the config as signing: { secret: whsec_… } and start the app with the same value, but only if the
app under test runs inside the CI job. A committed secret is public, so never let a preview, staging or
production deployment accept it.
Pulling fresh fixtures in CI
test run --fresh pulls fixtures into a temporary directory first, using the config's pull: block,
and runs those instead of the committed ones. It needs a HOOKBASE_API_KEY (a read-only key is
enough):
- name: Webhook tests against the latest events
run: npx --yes @hookbase/cli@2 test run --fresh --wait-for http://localhost:3000
env:
HOOKBASE_API_KEY: ${{ secrets.HOOKBASE_API_KEY }}
HOOKBASE_TEST_SIGNING_SECRET: ${{ secrets.HOOKBASE_TEST_SIGNING_SECRET }}Committed fixtures stay the default for pull requests: nobody reviews fresh fixtures, fork pull
requests don't get the API key, and a run that depends on today's traffic isn't repeatable. --fresh
suits a scheduled job or a run on main that tells you when new payloads break your app. Then pull
those fixtures, review them and commit them.
What the Scrubber Does
Hookbase scrubs every fixture before it leaves Hookbase. It applies, in order:
- your redaction policies for deliveries;
- the source's masked and encrypted fields;
- built-in detection, by key name and value format: emails, phone numbers, names, handles, street addresses, cities, postal codes, IP addresses, dates of birth, government ids, card numbers and secrets;
- the paths you name with
--scrub(orpull.scrub); - the route's transform;
- a last pass over the output for emails, IP addresses and secret-looking values.
Catalog samples are the provider's published examples, not your customers' data, so steps 3 and 6 don't run on them.
Values are replaced with realistic fakes in the same format: a phone number keeps its country code, a card number keeps its length and a valid check digit. Fakes are stable within your organization, so the same email gets the same fake on every pull and fixtures stay consistent with each other.
The scrubber also leaves things out:
- The values of the destination's auth headers and custom headers never leave Hookbase (apart from
plain
Content-Type,AcceptandUser-Agentvalues). The fixture lists them by name inomittedHeaders. If your app needs one, set it underheaders:in the config, from an environment variable. - Signatures and delivery ids are not in fixtures.
test runadds new ones. - Secret-looking segments of the destination's URL path become
:redacted, and secret query values becomeredacted.
Its limits
- Free text isn't checked for names. Emails, IP addresses and secret-looking values are replaced
wherever they appear, but a name or address written in a
description,note,messageor similar field stays. The scrub report warns about these fields. - Ids and business values stay. Provider ids (
cus_…,pi_…), amounts, currencies, countries, timestamps and booleans are left alone, because handlers depend on them. A provider id can still identify a customer to someone with access to that provider account. --keep <path>leaves a value the built-in detection would replace. It can't override a redaction policy or the source's masked fields.
Review every file before committing it. The report is in the file itself, under scrub.fields and
scrub.warnings. To scrub a field the detection missed, add it with --scrub '$.path' (or
--scrub '$.path=name' for a fake of that kind) and pull again with --update refresh.
Keeping fixtures current
| Command | What it does |
|---|---|
hookbase fixtures pull | Adds fixtures for event types you don't have yet and leaves existing files alone |
hookbase fixtures pull --update refresh | Renders the fixtures on disk again, for example after a transform change |
hookbase fixtures pull --update replace --force | Deletes the destination's fixtures and pulls a new set |
--dry-run shows what would change. An event past your plan's retention can't be refreshed, so its
fixture is kept as it is and the CLI says so. Every pull that returns fixtures is recorded in the
audit log as destination.fixtures_exported.
Exit Codes
| Code | Meaning |
|---|---|
0 | Every fixture passed or was skipped |
1 | A fixture failed or couldn't be sent, or the --wait-for URL never became ready |
2 | Invalid config, fixtures or flags, including a missing signing secret or no fixtures (pass --allow-empty to accept none) |
3 | A Hookbase API error, from fixtures pull or test run --fresh |
Security
- Treat
hookbase.tests.yamlas code. It decides where fixtures are sent and which headers they carry, and itsexprrules run inside the CLI. Review changes to it like any other code. - Don't run
test runon untrusted code in a job that has secrets. In GitHub Actions, that means not checking out a pull request's code in apull_request_targetworkflow and running the tests there. Usepull_request, which doesn't give fork pull requests your secrets. - The config can't read credentials.
${…}refusesHOOKBASE_API_KEY, the signing secret's variable,GITHUB_TOKEN,GH_TOKEN,CI_JOB_TOKENand the runner'sACTIONS_*variables, so a changed config can't send them to another URL. A target URL with a username or password in it is refused; set anAuthorizationheader underheaders:instead. - Keep the test secret separate. It's for test environments only (see step 2).
- Give CI a read-only API key if it uses
--fresh. It is enough forfixtures pull.
Related
- CLI commands: every flag of
fixtures pull,test runandtest init - Destinations: verifying deliveries
- Testing webhooks: test events, tunnels and request bins
- Fixture JSON Schema