Answer
Whistle provides powerful data mocking capabilities that can simulate interface return data during frontend development, improving development efficiency.
Data Mocking Methods
1. Using resBody Operator
Directly specify mock data:
shellwww.example.com/api/user resBody://{"code":0,"data":{"name":"Zhang San","age":25}}
2. Using Values Files
Create Values files to store mock data:
Create file: mock-user.json
json{ "code": 0, "data": { "id": 1, "name": "Zhang San", "age": 25, "email": "zhangsan@example.com" } }
Configure rule:
shellwww.example.com/api/user resBody://{mock-user.json}
3. Using resScript to Dynamically Generate Data
Create script file to dynamically generate responses:
Create file: mock-user.js
javascriptmodule.exports = function(req, res) { const userId = req.query.id || 1; res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ code: 0, data: { id: userId, name: `User${userId}`, timestamp: Date.now() } })); };
Configure rule:
shellwww.example.com/api/user resScript://{mock-user.js}
4. Using Whistle Plugins
Develop whistle plugins to implement more complex mocking logic:
javascriptmodule.exports = function(server, options) { server.on('request', function(req, res) { if (req.url === '/api/mock') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ mock: true })); } }); };
Advanced Mocking Techniques
1. Delayed Response
shellwww.example.com/api/* resScript://{delay-response.js}
delay-response.js:
javascriptmodule.exports = function(req, res) { setTimeout(() => { res.end(JSON.stringify({ code: 0, data: 'success' })); }, 2000); // 2 second delay };
2. Error Simulation
shellwww.example.com/api/error resBody://{"code":500,"message":"Server Error"}
3. Conditional Mocking
Return different data based on request parameters:
javascriptmodule.exports = function(req, res) { const type = req.query.type; let data; if (type === 'success') { data = { code: 0, message: 'Success' }; } else if (type === 'error') { data = { code: 500, message: 'Failure' }; } else { data = { code: 400, message: 'Invalid Parameter' }; } res.end(JSON.stringify(data)); };
Best Practices
- Use Values files to manage static data
- Use resScript to handle dynamic data
- Organize mock data by functional modules
- Add comments to explain the purpose of mock data
- Regularly clean up unused mock rules