乐闻世界logo
搜索文章和话题

How does whistle implement data mocking and what are the common mocking methods?

2月21日 16:26

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:

shell
www.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:

shell
www.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

javascript
module.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:

shell
www.example.com/api/user resScript://{mock-user.js}

4. Using Whistle Plugins

Develop whistle plugins to implement more complex mocking logic:

javascript
module.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

shell
www.example.com/api/* resScript://{delay-response.js}

delay-response.js:

javascript
module.exports = function(req, res) { setTimeout(() => { res.end(JSON.stringify({ code: 0, data: 'success' })); }, 2000); // 2 second delay };

2. Error Simulation

shell
www.example.com/api/error resBody://{"code":500,"message":"Server Error"}

3. Conditional Mocking

Return different data based on request parameters:

javascript
module.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

  1. Use Values files to manage static data
  2. Use resScript to handle dynamic data
  3. Organize mock data by functional modules
  4. Add comments to explain the purpose of mock data
  5. Regularly clean up unused mock rules
标签:Whistle