In this blog, you will learn to understand how to perform API testing for GET and POST in cypress with code and output.
What is an API?
API(Application Programming Interface) In software application (app) development, Although API is the middle layer between the presentation (UI) and the database layer. Above all APIs enable communication and data exchange from one software system to another.
What is Cypress?
Cypress framework is a JavaScript-based end-to-end testing framework built on top of Mocha – a feature-rich JavaScript test framework running on and in the browser, making asynchronous testing simple and convenient.
Therefore, it also uses a BDD/TDD assertion library and a browser to pair with any JavaScript testing framework.
What is an API Testing?
It is a software testing practice that tests the APIs directly from their functionality, reliability, and performance, to security.In addition it effectively validates the logic of the build architecture within a short amount of time known as API testing.
Get Method in Cypress:
To perform a Get operation, we shall make an HTTP request with the cy.request() whereas pass the method GET and URL as parameters to that method.
The status code reflects although the request has been accepted and handled correctly. However the code 200(means ok) and 201(means created).
Implementation of GET Method in API testing:
The implementation of GET method in Cypress is explained below −
describe('API testing for GET and POST in cypress',function(){
it('GET Method',function(){
cy.request("GET", "https://reqres.in/api/users/2", {
}).then((r) => {
expect(r.status).to.eq(200)
expect(r).to.have.property('headers')
expect(r).to.have.property('duration')
});
})
})
Output:
Post Method:
While using the POST method, Whenever we actually sending information.
If we have a group of entities , we can append new ones at the end, with the help of Post.
To perform a POST operation, we shall make an HTTP request with the cy.request() and pass the method Post and URL as parameters to that method.
Implementation of POST Method in API testing:
Given below is an implementation of POST method in Cypress −
describe('API testing for GET and POST in cypress',function(){
it('Post Method',function(){
cy.request({
method: 'POST',
url:"https://reqres.in/api/users",
body: {
"name": "morpheus",
"job": "leader"
}
}).then((response)=>{
expect(response.status).to.equal(201)
})
})
})
References:
https://www.tutorialspoint.com/cypress/index.htm
https://docs.cypress.io/guides/overview/why-cypress
