Testing

Up until now, we have introduced unit tests to validate that the code is working as expected. However, we would like to add even more tests. After all, the more tests we include in our system, the more confidence we will gain.

Since we are writing a rest API, we will create a simple script that will exercise our endpoints from time to time, giving us the confidence that the app is always working. To achieve this goal, our tests will follow a simple process:

  1. Authenticate the user using the endpoint.
  2. Validate the status code from the response.
  3. Take the token from the response body.
  4. Hit the balance endpoint using the token.
  5. Validate the status code from the response.

The easiest way to achieve this goal is by using Postman ( https://www.getpostman.com/). This is a handy tool that allows for trying RESTful web services, and creating tests for them, as well.

Let's discuss the test generated for the endpoint to authenticate a user, as shown in the following screenshot:

Test for the authentication endpoint in Postman

The first three lines of the preceding code check the retrieved status code, and line 5 stores the retrieved body response as a variable named jwt-token.

Using the preceding code, we can later inject the value of this variable into the subsequent requests and perform whatever validations we want. 

Once all of the tests have been created, we can generate a link referring to the collection that contains them, as shown in the following screenshot:

Postman collection link

With this link, the collection of tests can be executed over and over again, using a command-line integration runner named Newman (https://www.npmjs.com/package/newman) and the following command:

newman run https://www.getpostman.com/collections/8930b54ce719908646ae

The following screenshot shows the results of the Newman command's execution:

The results of the Newman command execution

This tool can be integrated with any CI server, such as Jenkins, to schedule jobs in charge of verifying the health of the application regularly, which will give us the confidence that our app is always working.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.70.170