-
Notifications
You must be signed in to change notification settings - Fork 1
Creating a dynamic mock with javascript
In this section, we'll delve into creating a new mock that diverges from static behavior. This time, the content of the mock will be dynamically resolved upon each request. Imagine simulating an actual endpoint that responds with random greeting messages in plain text.
The key element in this endeavor is the Response Body Type
set as Javascript
. You'll witness how effortlessly we achieve the mock's dynamic nature.
Commence by creating a new mock, as shown below:
Proceed to complete the Response Body Content
as depicted in the following JavaScript snippet:
let greetings = [
"Hi there!",
"Hey, how's it going?",
"Hiya! Ready to dive in?",
"Well, hello! Let's get started.",
"Hello, dear friend!",
"Greetings! What's on your mind today?",
"Hi, lovely human!",
"Hey, stranger! Ready to chat?",
"Hi, hi! What's the latest scoop?",
"Ahoy! How can I assist you today?",
"Hi, sunshine! What brings you here?",
"Hello from the other side! How can I help?",
"Hi there, adventurer! Ready for a journey?",
"Hey, superstar! What's the plan for today?",
"Hi, curious mind! Let's explore together.",
"Greetings and salutations! How can I assist?",
"Hi, my friend! What's the good word?",
"Hey, champ! Ready to conquer the day?",
"Hi, fellow explorer! What's your quest today?",
"Hello, kind soul! How can I brighten your day?"
];
function getRandomElementFromArray(array) {
if (array.length === 0) {
return "Hi there!!!";
}
const randomIndex = Math.floor(Math.random() * array.length);
return array[randomIndex];
}
const randomGreeting = getRandomElementFromArray(greetings);
return randomGreeting;
Additionally, note that the response's Content type has been chosen as application/text
, though you have the freedom to select any suitable option based on your needs.
With these steps completed, let's observe the outcome. Assuming your application is running on port 8080
, navigate to http://localhost:8080/api/greeting
.
This walkthrough showcases the creation of dynamic mocks through JavaScript, offering you the ability to generate varied responses for your API endpoints.
Next: Create a dynamic mock using query parameters and path variables with javascript