DEV Community

Cover image for Mastering Cypress API Testing: A Comprehensive Guide with Examples
Steve Wortham
Steve Wortham

Posted on

Mastering Cypress API Testing: A Comprehensive Guide with Examples

Application Programming Interface, popularly called as APIs are an important aspect of software development lifecycle not only from the dev point of view but also from the testing perspective. These APIs facilitate interaction between different systems to exchange data. Hence, it becomes extremely important to test these APIs thoroughly to ensure seamless functioning of the application.

In this article we will explore API Testing with Cypress Testing Framework and see how we can automate our APIs for efficient testing. We will cover below points in this article-

Overview of API Testing

API testing involves sending the HTTP Request, be it the GET, POST, PUT, DELETE(or other methods) to the backend server and retrieving the responses. Once the responses are retrieved they are validated to ensure that the expected values have been received. Some key aspects of API testing are listed below

  • Verifying the Status Code – Validation of the status code in the response is done to ensure that the desired status code is being received. For example, 200 status codes are expected to ensure Success. You can refer to other standard status codes used for HTTP Requests from the wiki documentation.
  • Response Body Assertions – Validation of the HTTP response body to ensure that the XML or the JSON contains the expected data and has the correct structure.
  • Testing the Request Parameter – Validation of the behaviour of API by passing different values in the parameters and the headers.
  • Authentication & Authorization – Validation of proper authentication mechanism and security aspects. While testing the APIs, the above points are considered to ensure that the end-to-end functioning of API is bug free.

Utilising Cypress for API Testing

Cypress is a popular front-end testing tool, used for browser and end-to-end automation testing. Cypress comes with network request capabilities, which makes it a good choice for API testing as well. Some of the key features offered by Cypress for API Testing are-

  • Familiarity in syntax – Similar to the UI tests, Cypress API commands use the same .should() and .then() syntax.
  • Built-In Assertions – We can easily use the assertions provided by Cypress to assert the status code, or headers or even the response body of API requests.
  • Retrying failed requests – Cypress automatically retries the failed requests to ensure that there is no network or other similar issue.

Elaborate Documentation – Cypress has nicely documented requests and assertions making it easy to get support on the run.

Key Features of Cypress API Testing

Cypress comes with a variety of features to help you perform API Testing effectively and efficientl. A few features are discussed below-

  • cy.wait() – Provides a mechanism to wait for a network request, and helps load asynchronous data.
  • cy.route() – Helps to route test requests to specific handlers.
  • cy.server() – helps to maintain an entire server for a test suite.
  • Test Runners – Help in parallel execution of tests for quick turnaround time.
  • cy.login() – Helps in making secured API requests by setting authorization headers with a single command before the calls.
  • cy.intercept() – Controls the responses, or simulates the behaviour by intercepting the requests. With these features it becomes very easy and convenient for the user to start writing the API tests with enhanced capabilities and efficient framework.

Now that we understand how Cypress can help in automating our APIs let us write a simple API Test using Cypress. But before that you need to ensure that below prerequisites are fulfilled-

  • Install an IDE like Visual Studio (this is the most used IDE, but you may refer some other IDE like IntelliJ as well)
  • Install Node.js in your system Let us now walk through the steps of writing our first API test using Cypress.

Writing the First API Test using Cypress

In this article we will cover a simple scenario of sending HTTP Requests using the GET, POST, PUT, and DELETE methods. But before we start writing the test script we will set up the environment.

  1. Create a folder locally in your system, I have created a folder called CypressAPITests in my system.

Image description

cypress api
2 . Next, open the Visual Studio Code editor and open the folder as created in Step#1.

Image description

3 . Now that you have opened the folder, the next step is to set up the node project. To do so, in the terminal use the command npm init -y, this will create a package.json file.

Image description

4 . We will now install Cypress from the terminal, if not already done, using the command npx cypress install.

Image description

5 . We will now create the configuration files for our test, and to do so, we will run the command npx cypress open in the terminal.

Image description

6 . Once the Cypress tool opens up, select E2E Testing.

Image description

7 . Click on Continue on the next screen.

8 . Once the configuration files have been set up, go back to the Visual Studio Code editor and you will see a config file has been created.

Image description

9 . Now Cypress has been installed successfully and also the environment is all set. We will begin writing our tests now.

We will be using some dummy API calls to demo the Cypress API Automation.

In the Visual Studio Code editor, create a folder e2e under the Cypress directory. Under the e2e folder you can create another folder by the name of APITests. Note that you may select the folder name as per your requirement.

Now we will start writing our first test file. We will create a file under the APITests folder. Let us name it as HttpGetRequest. This file name will have an extension of .cy.js as shown in the snapshot below-

Image description
Now we will start writing the main code. Before doing that let us look at the basic syntax of the request-

cy.request(METHOD,url,body)

In the request made using Cypress, the url is a mandatory parameter but other parameters like Method and body are optional. You may look at the different request syntax from the official documentation of Cypress to get more understanding on how we can use it differently.

In our example scenario, we will be using the GET method to fetch some resources, so we will use the Method and the url as the parameters to cy.request.

cy.request('GET','https://dummy.restapiexample.com/api/v1/employees')
This command will make the API call to the server.

Next, we will assert some response value, for example the status code.

.its('status')
.should('equal',200);
This line of code will validate the response status code and assert that its value is 200.

Let us look at how this code will look once it is brought together:

describe('HTTPGet',()=>{

it('GET request',()=>{

cy.request('GET','https://dummy.restapiexample.com/api/v1/employees')
.its('status')
.should('equal',200);

})

})
After writing the code for a GET request we will execute the same. To execute it, we can use any of the two ways-

  1. Execution through terminal
  2. Execution through Cypress tool We will see one by one how we can perform the execution.

Execution through Terminal

To execute the Cypress code through terminal, open the terminal window and simply pass the command:

npx cypress run –spec “filepath”

In the above command the file path is the relative path of the file you would want to execute. Below snapshot shows the execution of HTTPGetRequest file on my system-

Image description

You can see that the test execution was successful and our API test has passed.

Let us now try executing the same test through the Cypress Tool.

Execution through Cypress Tool

1 . Simply write the command npx cypress open to open the tool.

  1. Once you see the tool window opened up, click on E2E Testing.

Image description

  1. Now select any browser. I am selecting Electron.

Image description

  1. You will see that the Electron browser opens up with the specs that we have written the Visual Studio Code being displayed.

Image description

  1. Select the HttpGetRequest and you will see that the execution begins with logs being displayed.

Image description

And there you have executed your first Cypress API Automation Test. We will now enhance our code to execute a couple of other HTTP Methods.

POST Method

Code to execute the POST HTTP Request-

describe('HTTPGet',()=>{

it('POST request',()=>{
cy.request({
method: 'POST',
url: 'https://dummy.restapiexample.com/api/v1/create',
body: {
"name":"test post",
"salary":"1234",
"age":"23"

}
})
.its('status')
.should('equal',200);
})
})
Upon, executing the above code the logs will be displaying the execution results as shown below-

Image description
For our next demonstrations we will use another fake API collection and see how the HTTP request methods work for them.

PUT Method

Code to execute the PUT HTTP Request-

describe('HTTPPut',()=>{

it('PUT request',()=>{
cy.request({
method: 'PUT',
url: 'https://jsonplaceholder.typicode.com/posts/1',
body: {
id: 1,
title: 'This is PUT Update',
body: 'This is PUT Update body',
userId: 1,
}
})
.its('status')
.should('equal',200) ;
})
})

Execution result of the above code are displayed below-

Image description

DELETE Method

Code to execute the Delete HTTP Request(Note that I appended the below piece of code in the same example I used above)-

it('DELETE request',()=>{
cy.request({
method: 'DELETE',
url: 'https://jsonplaceholder.typicode.com/posts/1',
})
.its('status')
.should('equal',200) ;
})
Since both PUT and DELETE request were in the same file, both the methods got executed and the results are as displayed below-

Image description
So, this is it and you now know how you can execute the basic HTTP Requests for different Methods using Cypress. You may now go ahead and try to implement Cypress API Testing in your projects and see how easily you are able to test the APIs with quick turnaround times.

Conclusion

After having gone through the basics of API and Cypress for API Testing we with conclude on below points-

  1. Cypress API Testing helps with a powerful set of tools which provides familiarity to Cypress’ syntax for UI Tests.
  2. We can use assertions conveniently to validate the response status code and any other response parameter.

Source: This article was originally published at testgrid.io.

Top comments (0)