Skip to content

Creating a dynamic mock with Javascript

Lazarus Lazaridis edited this page Nov 17, 2017 · 3 revisions

Now we will create again a new mock but this time it will not be static. Its content will be being resolved each time upon request. Suppose that the real endpoint that we will mock responds with JSON containing information about the reading status of a user for a specific book.

The script type that we are going to use is Javascript and you will soon see how easily we will accomplish the dynamic behavior of the mock.

Create a new mock as shown here: DuckRails dynamic mock general tab

Important note: mind the path. As you can see, it contains two variables, the :username and the :book_title. Since we are going to use a script to resolve the body content, we have access to the request's parameters thus if we want to use these variables, all we have to do is to fetch their value via the parameters variable. Don't worry, you will understand once you see the code snippet below.

Now fill in the Response body tab fields as shown here: DuckRails dynamic mock response body tab

As you can see, we set Body type to Javascript and filled in the Body content with

var date = new Date();
date.setDate(date.getDate() -  Math.floor(Math.random() * 30 + 1) );

var obj = {
  "username": parameters['username'],
  "book": parameters['book_title'],
  "current_page": Math.floor((Math.random() * 456) + 1),
  "started_reading": date.toDateString()
}

return JSON.stringify(obj);

In our JSON response, we defined that the username and the book will be those passed as variables in the path. We also respond with a current_page attribute which is being computed at the moment of the request as a random number. Finally, we include a started_reading attribute which again we resolve at the moment of the request by subtracting random days from the date the request occurs.

Also, note that we chose application/json as the response's Content type (you can of course pick whatever you want from the list based on your needs).

Now, let's see what we created. Given that your application is started on port 8080, navigate to http://localhost:8080/my-dynamic-mock/users/iridakos/books/sapiens. Tadaaaaaaa

DuckRails dynamic mock request