Stateful data with code-based mocks
Code-based mock servers provide a lightweight global state object. What you store in it is kept between requests, which makes it easy to simulate persistent data:
mock.post('/users', (req, res) => {
if (!req.body.username) {
return res.status(400).json({ status: "error", details: "Missing username" });
}
state.users = state.users || [];
state.users.push(req.body);
return res.status(200).json({ status: "ok" });
});
mock.get('/users', (req, res) => {
res.json(state.users || []);
});How state behaves
stateholds plain JSON data, up to 2 MB.- It belongs to the mock server, and it is kept when you overwrite the mock and when it follows a branch.
- It is deleted when you revoke the mock server.
- See the current state in the mock’s State view, or with
GET /apigit-mockserver-state.
⚠️
state is loaded fresh for each request, so read it inside your route handlers. A reference kept outside a handler, such as const users = state.users at the top of a file, is not updated by later requests.
Spec-based mock servers keep no state: each answer comes from the document alone.
Last updated on