Show List

Advanced simulations with Hoverfly

Hoverfly supports templating and JavaScript middleware, which allow developers to create dynamic responses and modify requests and responses in real-time.

Here's how to use these features in Hoverfly:

  • Templating: Hoverfly's templating feature allows you to create dynamic responses by defining placeholders in the response body that can be replaced with actual values during the simulation. To use templating, you need to define a template file in JSON format that specifies the placeholders and their replacement values. For example, if you want to replace the string "{{name}}" with the actual name of a user, you can define the following template:
json
Copy code
{ "name": "John Doe" }

Then, in your response body, you can use the placeholder "{{name}}" to represent the name field. When Hoverfly receives a request, it will replace the placeholder with the actual value from the template file, and return the modified response to the client.

  • JavaScript Middleware: Hoverfly also allows you to use JavaScript middleware to modify requests and responses in real-time. To use JavaScript middleware, you need to define a JavaScript file that exports two functions: onRequest and onResponse. These functions will be called by Hoverfly whenever a request or response is received, and you can use them to modify the request or response in any way you like. Here's an example of a JavaScript middleware that adds a custom header to the response:
javascript
Copy code
module.exports = { onRequest: function(request, response) { // Modify the request object here }, onResponse: function(request, response) { // Modify the response object here response.headers['X-Custom-Header'] = 'Hello, world!'; } };

In this example, the onResponse function adds a custom header to the response with the value "Hello, world!". When Hoverfly receives a request, it will call the onResponse function, modify the response object as specified in the function, and return the modified response to the client.

Overall, both templating and JavaScript middleware are powerful features that can help developers create dynamic responses and modify requests and responses in real-time. By using these features, developers can create more realistic simulations and test their applications more thoroughly.


    Leave a Comment


  • captcha text