API Testing with Cypress

API Testing with Cypress

Gone are the days of relying solely on UI-based tests. With the rise of APIs, it's become essential to test their functionality, reliability, performance, and security to ensure that they live up to the expectations of both the developers and end-users—That's where API testing comes in. It allows you to test the functionality of APIs in isolation, without having to wait for the UI to be created.

API testing has become a critical aspect of software testing, and using Cypress for API testing, automating your testing process with ease is simpler than ever! But how do you go about automating your API testing using Cypress? Don’t worry! It’s easy. 

We'll walk you through the general steps of installing Cypress, setting up your project, and writing. 

 

What is Cypress in Testing?

what is cypress in testing

What is cypress test automation tool: Cypress is an end-to-end testing framework for web applications that allows you to automate browser interactions. It is built on top of JavaScript and can be used to test web applications built with any framework or library. 

Cypress provides a simple and intuitive API for interacting with web pages, and it can be integrated with other tools such as Mocha and Chai for test assertion and reporting. Additionally, Cypress has its own built-in test runner and debugging tools, making it a powerful and easy-to-use tool for automating web application testing. 

So to answer your question on what is cypress testing tool, you should know that this tool is very handy. With its convenient installation process, built-in features, real-time feedback, and control over the browser, Cypress makes it simple to write and run test scripts, resulting in better test coverage and faster feedback.

 

Why to use Cypress for automation testing?

There are several reasons to use Cypress for automation testing:

  1. Easy to set up: One of the reasons to use Cypress is its simple installation process that does not require any additional configuration.
  2. Built-in features: Cypress includes a test runner, assertion library, and automatic waiting, making it easy to write and run test scripts.
  3. Real-time feedback: Cypress provides real-time feedback during test runs, making it easy to debug and troubleshoot issues.
  4. Control over browser: Use Cypress for automation to runs tests directly in the browser, giving the test writer full control over the browser and the ability to interact with it as a user would.
  5. Better test coverage: Cypress enables you to test both the front-end and back-end of an application, resulting in better test coverage.

These are just some of the reasons to use Cypress in a smart and efficient way. 
 

Stey by step automation in Cypress 

To carry out the Cypress automation setup, you can follow these general steps:

  1. Install Cypress: Step by step automation in Cypress involves installing Cypress.  Run npm install cypress in your project's root directory.
  2. Set up your project: Cypress requires a specific file structure for your project, so you'll need to set up your project accordingly. Cypress will look for a cypress directory in your project, and within that directory, it will look for an integration directory.
  3. Write test scripts: Cypress uses JavaScript to write test scripts, which are essentially a series of commands that simulate user interactions with your web application. You can use Cypress's built-in commands, such as cy.visit(), cy.get(), and cy.click(), to navigate to a webpage, select elements, and interact with them.
  4. Run the tests: Once you have written your test scripts, you can run them using the Cypress Test Runner. You can open the Test Runner by running npx cypress open in the command line.
  5. Assertions: Cypress provides its own assertion library to make assertions about the state of your application. You can use cy.should() to make assertions about the value or state of an element.
  6. Debugging: Cypress provides a powerful debugging tool that allows you to interact with the browser as you step through your test. You can use the browser's developer tools to inspect elements and debug your test scripts.
  7. CI/CD integration: Cypress can be integrated with other tools, such as Jest and Mocha, and can also be used in continuous integration and deployment (CI/CD) pipelines.

That’s how you conduct a Cypress step by step setup! 

 

What is API Testing?

what api testing

If you want to know what API testing is, it is a form of software testing that focuses on the testing of application programming interfaces (APIs). It is accomplished as a part of integration testing to determine if the system is able to satisfy functionality, reliability, performance, and security expectations. 

API testing has recently been considered critical to the software testing process as it is faster and more reliable than UI-based tests. An API is a set of protocols, routines, and tools for building software and applications, and it defines how different software components should interact with each other.

  • API testing allows the testers to find bugs earlier in the development process, usually before the UI is created. 
  • API testing allows requests that might not be allowed through the UI as sometimes, the UI is not ready during API development.

 

Where Can API Testing be Done?

To know where can API testing be done, you need to first know that API testing can be performed at different levels, including:

  • Unit testing: Testing the individual components of an API to ensure they work as expected.
  • Integration testing: Testing how different components of an API work together to ensure they are integrated correctly.
  • Functional testing: Testing the functionality of an API by sending input and verifying the output.
  • Performance testing: Testing the performance of an API to ensure it can handle a high volume of requests and responses in a timely manner.
  • Security testing: Testing the security of an API to ensure it is protected against potential threats such as hacking or data breaches.

 

The importance of API testing in software development cannot be stressed enough.  The purpose of API testing is that it connects different systems and applications, and ensures that they work together seamlessly. The importance of API testing can also be witnessed in how it helps identify bugs early in the development process, improve the performance and scalability of the system, and ensure that the system is secure and reliable.


 

What to know about API Endpoints?

You may be wondering what does API endpoint mean? An API endpoint is the entry point in a communication channel where two software mediators interact. The endpoint can be seen as how the APIs can access the resources they require from a server to fulfill their tasks. An API endpoint is a fancy word for a server or service URL. For example, https://api.linkedin.com/v2/simpleJobPostings is the endpoint for LinkedIn’s job posting API.

 

Methods Supported

We need to understand the methods (POST, GET, PUT, DELETE, PATCH) supported by the API. Keep in mind those as we need to test them.

 

Input-Output Schema

It is essential to comprehend the type of input required and the response body content for the API (JSON, plain text, XML, or other).

 

Response Codes in API Testing 

The response codes in API testing or status code is the most crucial API output that must be verified. The API response status codes are included in five classes or types. The first digit of the response code represents the response class, while the last two digits do not have any classification or categorization roles. The standard defines five types of API response codes:

  • 1xx Informational response – the request was received, resuming the process.
  • 2xx Successful – the request was received, comprehended, and accepted.
  • 3xx Redirection – further action must be taken to complete the request.
  • 4xx Client error – the request contains the wrong syntax or cannot be fulfilled.
  • 5xx Server error – the server failed to fulfill a valid request.

 

Headers and Auth Requirements

API calls demand a variety of header fields. Headers include a wealth of information that can help track down issues when they occur.

Typically, headers contain information regarding the request, response body, and request authorization. In addition, authentication is essential to confirm the credentials of a connection attempt. Therefore, most commercial APIs require API Key-based Authentication for their services.


 

Using Cypress for API Testing

When using Cypress for API testing, you should know that as Cypress is a standalone frontend testing tool, it makes HTTP requests on behalf of the web applications at the time of execution. While it might appear that Cypress is making these requests from the browser, it actually uses node.js as an engine to make the HTTP requests to the API server. It uses Node.js to return the responses received from the server. 

using cypress for api testing

 

Sample API Test

Let's look at an API test sample to understand better how to test API using Cypress.

context("GET /users", () => {

  it("A list of users", () => {

    cy.request("GET", "/users").then((response) => {

      expect(response.status).to.eq(200)

      expect(response.body.results).length.to.be.greaterThan(1)

    })

  })

})

 

In the sample test, we are making a GET request to our ‘/users’ route using cy.request(). We assert that the response returns a 200 status code and that more than one user is returned from the response.

 

Here are some more examples of API testing for other types of requests.

Sample for testing POST request:

it('POST-Create user',()=>{

        var user = {

            "name": "Vandana Yadav",

            "job": "QA"

        }

 

        cy.request('POST','/users',user).then((response)=>{

            expect(response.status).equal(201)

            expect(response.body.name).equal(user.name)

            expect(response.body.job).equal(user.job)

 

        })

        cy.request('POST','/users',user).its('body').should('include',{name:'Vandana Yadav'})

})

 

Sample for testing PUT request:

it('Update user',()=>{

        var user1 = {

            "name": "Samantha",

            "job": "DevOps"

        }

 

        cy.request('PUT','/users/2',user1  ).then((response)=>{

            expect(response.status).equal(200)

            expect(response.body.name).equal(user1.name)

            expect(response.body.job).equal(user1.job)

        })

})

 

Sample for testing Delete request:

it('Delete user',()=>{

        var user1 = {

            "name": "Samantha",

            "job": "DevOps"

        }

 

        cy.request('DELETE','/users/2').then((response)=>{

            expect(response.status).equal(204)

 

        })

    })

})

 

We hope this blog has made it easier for you to understand how using Cypress for API testing becomes convenient. If you want to learn more about API testing using Cypress or learn about how Cypress can help you improve your testing coverage and speed up your feedback, contact our QA experts. Our professionals are meticulous and help you build better web applications, one test at a time.

Zahin Ahad
Zahin Ahad
Jr. SQA Engineer
Happiness in helping others

Happiness in helping others

Anuj Azrenkar
Learn how to Build Productivity Application With ReactJs

How To Build A Simple Productivity Application With ReactJs

Makdia Hussain
Tips for Building a Positive Environment

Significance of positive work environment

Rishabh Talauliker