Skip to content

A stateful mock server in JavaScript: answers that remember earlier requests

Last checked and updated

A mock generated from an API description is stateless: it answers each request from the description and remembers nothing. For a flow such as "add two items, then read the cart", the mock needs code. A code-based mock is a set of Express routes in one file, plus a state object that survives between requests.

The whole mock

apigit-mock/main.js:

mock.post('/cart/items', (req, res) => {
  if (!req.body.sku) {
    return res.status(400).json({ error: 'sku is required' });
  }
  state.cart = state.cart || [];
  state.cart.push({ sku: req.body.sku, quantity: req.body.quantity || 1 });
  res.status(201).json({ items: state.cart.length });
});

mock.get('/cart', (req, res) => {
  const cart = state.cart || [];
  res.json({ items: cart, total: cart.reduce((n, i) => n + i.quantity, 0) });
});

mock.delete('/cart', (req, res) => {
  state.cart = [];
  res.status(204).end();
});

mock is an Express 4 app that is already set up: JSON bodies are parsed and CORS is enabled. state is a plain object for JSON data.

Run it

$ apigit mock serve ./apigit-mock --port 4652
Code-based mock of apigit-mock at http://127.0.0.1:4652 (Ctrl+C to stop). It is loaded again when a file changes.
  ...

Editing main.js while it runs reloads the code and keeps the state; stopping the command empties it.

The sequence a test would make:

$ curl http://127.0.0.1:4652/cart
{"items":[],"total":0}

$ curl -X POST http://127.0.0.1:4652/cart/items -H 'content-type: application/json' -d '{"sku":"A1","quantity":2}'
{"items":1}

$ curl -X POST http://127.0.0.1:4652/cart/items -H 'content-type: application/json' -d '{"sku":"B7"}'
{"items":2}

$ curl http://127.0.0.1:4652/cart
{"items":[{"sku":"A1","quantity":2},{"sku":"B7","quantity":1}],"total":3}

The second read differs from the first because of the two requests between them. The mock's own rule applies too ({} gets 400 with {"error":"sku is required"}), and a path without a route answers 404 with {"error":"route not found","message":"route not found for /orders"}.

Looking at the state, and resetting it

The mock serves its state at a built-in route:

$ curl http://127.0.0.1:4652/apigit-mockserver-state
{"message":"Mock Server State","state":{"cart":[{"sku":"A1","quantity":2},{"sku":"B7","quantity":1}]}}

Tests need a known start. Give the mock a reset route of its own, as DELETE /cart above, and call it before each test: after it, GET /cart returns {"items":[],"total":0} again.

Two rules that save an afternoon

  1. Read state inside the handler. A copy taken at the top of the file (const cart = state.cart) is not updated by later requests: on a hosted mock the state is loaded for each request.
  2. Keep state small and plain. JSON only (no functions, no class instances), 2 MB on a hosted mock.

Generated or scripted

Mock generated from the descriptionScripted mock
Answers come fromthe examples and schemas of the API descriptionyour code
Remembers earlier requestsnoyes, in state
Validates requests against the descriptionyesonly what your code checks
Can drift from the API descriptionnoyes: it is separate code

Start with the generated kind (from an OpenAPI file, or from a GraphQL schema) and write code only for the flows that need memory. The script runs with your rights on your machine, like any Node.js script; a hosted mock runs it in an isolated sandbox without network access (hosted code-based mocks are part of APIGit's paid plans; the local command is free).

Sources

Related pages

Try it with your own API

Create a free workspace, add an OpenAPI file, and publish its documentation and a mock server from the same repository.

Free for individuals. No credit card.

$ npm install -g @apigit/cli$ apigit auth login$ apigit doc publish