Testing against the mocks, offline.

The mocks answer on the machine. Nothing leaves it, nothing is billed for it, and the answer is the same every time. This page is how to point a project at them, and how to drive the paths that only happen when something goes wrong.

Pointing an application at them

Every mock has an environment variable that points an application at it. The command line prints the value as the mock starts, so there is nothing to copy by hand.

MockEnvironment variable
stripeNUXT_STRIPE_API_BASE
resendNUXT_RESEND_API_BASE
xeroNUXT_XERO_API_BASE
cloudflareNUXT_CLOUDFLARE_API_BASE
paystackPAYSTACK_API_URL
interswitchINTERSWITCH_API_URL
youverifyYOUVERIFY_API_URL
onesignalONESIGNAL_API_URL
twilioTWILIO_API_URL
flutterwaveFLUTTERWAVE_API_URL
monnifyMONNIFY_API_URL
termiiTERMII_API_URL
smileidSMILEID_API_URL
identitypassIDENTITYPASS_API_URL
whatsappWHATSAPP_API_URL
fcmFCM_API_URL
openaiOPENAI_API_BASE
s3S3_ENDPOINT

The printed value carries the path each provider expects — /v1 for Stripe, /v3 for Flutterwave, /api.xro/2.0 for Xero, /client/v4 for Cloudflare, and /v1 for the model API.

Pointing a whole application at the stack is one line:

eval $(api-mock-services env)

It exports the variable for every mock in the stack, so an application that reads more than one of them needs nothing else.

Starting a category

The compose file is grouped into profiles, so a project only starts what it needs — a category of two or three containers rather than all eighteen.

docker compose -f examples/docker-compose.yml --profile payments up -d
docker compose -f examples/docker-compose.yml --profile identity up -d
docker compose -f examples/docker-compose.yml --profile messaging up -d
docker compose -f examples/docker-compose.yml --profile all up -d

The profiles are payments, identity, messaging, email, accounting, dns, ai, storage and all.

The lightest way of all is one container holding several mocks — one process, one image, several ports:

docker run --rm -p 4001:4001 -p 4005:4005 api-mock-services stripe paystack

The command line uses each mock's own port. The compose file publishes some of them on other ports — Paystack on 5001, for instance — so check the compose file if that is the route you take.

Writing a mock as a route file

Most providers are worth a hand-written mock, because their flows have state. But a service that is only read from does not — and for those, a route file is enough.

{
  "name": "acme",
  "state": { "greeting": "hello" },
  "routes": [
    { "method": "GET", "path": "/v1/things", "body": { "things": [] } },
    { "method": "GET", "path": "/v1/things/:id", "body": { "id": "{{params.id}}" } }
  ]
}

The same thing as a JavaScript module, which can compute:

import { createSpecMock } from '@bytesickle/api-mock-services'

const acme = createSpecMock({
  name: 'acme',
  routes: [
    { method: 'GET', path: '/v1/things', body: { things: [] } },
    { method: 'GET', path: '/v1/things/:id', body: { id: '{{params.id}}' } },
  ],
})

And a route file can be a file on disk, started from the command line:

api-mock-services file ./mocks/acme.json
KeyWhat it does
nameThe name of the mock.
stateThe state the mock keeps. A route can read it.
routesThe routes.
methodThe HTTP method. GET if it is left out.
pathThe path. A :name segment becomes a parameter.
statusThe status code. 200 if it is left out.
bodyThe body, with the placeholders filled in.
headersThe response headers.
rawThe body is sent as it is, rather than as JSON.

The placeholders

The placeholders are filled in from the request:

PlaceholderWhere it comes from
{{params.id}}The path.
{{query.q}}The query string.
{{body.email}}The body.
{{header.authorization}}A header.
{{state.anything}}What the mock keeps.

A route file cannot hold a payment in progress — that is what a mock written as code is for. A route file is JSON and a few placeholders, with no new dependency.

Driving the failure paths

The failure paths are the ones worth testing. Once a mock is running, it can be told what to do:

api-mock-services pay stripe failed       # the next payment fails
api-mock-services error stripe server     # the next call answers 500
api-mock-services error stripe timeout 3  # the next three calls time out
api-mock-services webhook stripe resend   # send the webhook again
api-mock-services reset stripe            # forget everything
api-mock-services logs stripe             # watch the requests

The kinds of failure are server, unauthorised, unavailable, timeout and network. The outcome of the next payment can be success, failed or cancelled.

The panel does the same things, and shows the requests as they come in. It is at /_panel on every mock:

http://127.0.0.1:4001/_panel

The buttons are real forms, so the page works even when the script does not load.

Worked examples

A card refund, in a test

import { startMock } from '@bytesickle/api-mock-services'

const stripe = await startMock('stripe')

process.env.NUXT_STRIPE_API_BASE = `${stripe.url}/v1`

// ... the test ...

expect(stripe.last().path).toBe('/v1/refunds')
expect(stripe.state.refunds[0].payment_intent).toBe('pi_test_1')

await stripe.close()

The mock remembers what it was asked, so the test can say what really happened. Nothing listens on a port and the mock stops when the test ends.

A gateway reference that decides the outcome

A reference with success in it comes back successful, one with failed in it comes back failed. A test can ask for either without a special flag.

curl -s http://127.0.0.1:4005/transaction/initialize \
  -H 'Content-Type: application/json' \
  -d '{"email":"you@example.com","amount":5000,"reference":"order_success_001"}'

curl -s http://127.0.0.1:4005/transaction/verify/order_success_001

The answer, trimmed:

{
  "status": true,
  "message": "Verification successful",
  "data": {
    "reference": "order_success_001",
    "amount": 5000,
    "status": "success",
    "gateway_response": "Successful",
    "channel": "card",
    "currency": "NGN"
  }
}

Change the reference to order_failed_001 and the same request answers failed, with Transaction failed as the gateway response.

A contributed mock, as a route file

The M-Pesa mock in contrib/ is a route file. It reads the body it was sent, and it reads its own state:

{
  "name": "mpesa",
  "state": { "greeting": "hello" },
  "routes": [
    {
      "method": "POST",
      "path": "/mpesa/stkpush/v1/processrequest",
      "status": 200,
      "body": {
        "ResponseCode": "0",
        "ResponseDescription": "Accept the service request successfully.",
        "CustomerMessage": "Success. CheckoutRequestID sent to your phone.",
        "CheckoutRequestID": "{{state.greeting}}",
        "MerchantCode": "{{body.BusinessShortCode}}",
        "TransactionDesc": "{{body.TransactionDesc}}"
      }
    }
  ]
}
api-mock-services file contrib/mpesa.json

Nothing in contrib/ is loaded by the package, and nothing in it has to be reviewed as JavaScript.

← CI gates Impact →