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-
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
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-
Elaborate Documentation – Cypress has nicely documented requests and assertions making it easy to get support on the run.
Cypress comes with a variety of features to help you perform API Testing effectively and efficientl. A few features are discussed below-
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-
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.
cypress api
2 . Next, open the Visual Studio Code editor and open the folder as created in Step#1.
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.
4 . We will now install Cypress from the terminal, if not already done, using the command npx cypress install.
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.
6 . Once the Cypress tool opens up, select E2E Testing.
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.
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-
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-
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-
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.
1 . Simply write the command npx cypress open to open the tool.
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.
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-
For our next demonstrations we will use another fake API collection and see how the HTTP request methods work for them.
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-
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-
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.
After having gone through the basics of API and Cypress for API Testing we with conclude on below points-
Source: This article was originally published at testgrid.io.
The above is the detailed content of Mastering Cypress API Testing: A Comprehensive Guide with Examples. For more information, please follow other related articles on the PHP Chinese website!