Mocking API endpoints is essential for front-end development when back-end services are not yet complete, enabling parallel development and improving efficiency. This guide demonstrates how to use mock data, using a tool similar to FastMock (though FastMock itself may currently be unavailable, the principles are widely applicable).
Basic Data Structure
To simulate a standard API response:
{
"code": 200,
"msg": "Query successful",
"data": {
"Title": "Simulated API Endpoint",
"Author": "Deer"
}
}
To generate multiple records with varying quantities:
{
"code": 200,
"msg": "Query successful",
"data|1-10": [
{
"id|+1": 1,
"name": "Deer",
"price|10-99.1-3": 0
}
]
}
Handling GET and POST Requests
Mocking dynamic responses based on request parameters is possible:
{
"code": 200,
"msg": "Query successful",
"data": function({_req, Mock}) {
let { id, name } = _req.query;
return {
id: id,
name: name
};
}
}
Simulating Response Headers
This is often used for scenarios like authentication:
{
"code": 200,
"msg": "Query successful",
"data": function({ _req, Mock }) {
let { token = null } = _req.headers;
if (token) {
return { code: 1, name: "admin" };
} else {
return { code: -1, msg: "Authentication error" };
}
}
}
Using Mock.mock() for Complex Data Generation
Mock.mock() can be used within a function to geenrate more intricate data structures:
{
"code": "200",
"msg": "Query successful",
"data": function({ _req, Mock }) {
let { list } = Mock.mock({
"list|3-8": [
{ "id": "@id", "name": "@cname" }
]
});
return list;
}
}
For POST requests where parameters influence the number of items retruned (e.g., a limit parameter), direct interpolation like "data|limit" is not permitted. Instead, construct the pattern dynamically:
{
"code": 200,
"data": function({ _req, Mock }) {
let { limit = 2, size = 0, hot = false } = _req.body;
let dynamicDataPattern = {};
let itemTemplate = { "_id": "@id" };
dynamicDataPattern["list|" + limit] = [itemTemplate];
return Mock.mock(dynamicDataPattern);
}
}
Common Generation Rule Formats
"data|5": Generates exactly 5 items."data|1-3": Generates a random number of items between 1 and 3."id|+1": Increments the ID for each generated item."price|10-99.1-3": Generates a random number between 10 and 99 with 1 to 3 decimal places."status|1": Ganerates a boolean value, withtruehaving a 50% probability.
Data Placeholder Examples
Utilize built-in placeholders for realistic data generation:
{
"code": 200,
"data|2-5": [
{
"id": "@id",
"name": "@cname",
"price|10-99.1-5": 0,
"status": "@boolean()",
"num": "@natural(18,50)",
"des": "@string(10,30)",
"time": "@datetime('T')",
"title": "@cword(10,40)",
"address": "@county(true)",
"prcurl": "@image('300x200', '@color', '#000', 'pic')"
}
],
"msg": "Query successful"
}