Open In App

Cypress API Testing

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In today's interconnected digital landscape, APIs (Application Programming Interfaces) play a crucial role in enabling seamless communication between different software applications. Whether it's a web service, a system interface, or a library, APIs are the backbone of most modern applications, allowing the frontend and backend systems to interact efficiently.

Given the critical importance of APIs, ensuring their reliability, performance, and security is essential. This is where API testing comes into play. API testing involves directly testing the APIs to verify that they function as expected under various conditions. It helps identify issues early in the development process, ensuring that the APIs meet the required standards before they are deployed to production.

What is an API?

An API (Application Programming Interface) is a set of rules that allows different software applications to communicate with each other. APIs define methods and data structures that developers can use to interact with the software, whether it's a web service, a library, or a system interface.

Purpose of API Testing

API testing involves testing the APIs directly to ensure they work as expected. This is crucial because APIs are the backbone of most modern applications, enabling the interaction between the frontend and backend systems. API testing helps ensure the reliability, performance, and security of these interactions.

Here's a step-by-step guide to executing the Cypress API testing article using Visual Studio with the command prompt as the terminal.

Setting up the Environment

Step 1: Install Node.js and npm

First, you need to ensure that Node.js and npm are installed. You can check this by running the following commands in the terminal:

node -v
npm -v

If Node.js is not installed, download and install it from official document from npm. This will also install npm.

1
Node.Js & Npm Installed successfully

Step 2: Create a New Project Directory

  • Open Visual Studio.
  • Open the terminal by navigating to View > Terminal.
  • In the terminal, create a new directory for your project and navigate into it
mkdir Cypress-Api-Testing
cd Cypress-Api-Testing

Step 3: Initialize a New Node.js Project

Run the following command to initialize a new Node.js project

npm init -y

This will create a package.json file in your project directory.

2
Initialize npm in Cypress-Api-Testing folder

Step 4: Install Cypress

Now, install Cypress as a development dependency by running:

npm install cypress --save-dev
3

Step 5: Open Cypress

Once installed, open Cypress to create the default directory structure:

npx cypress open

This will create a cypress folder with subdirectories like integration, fixtures, and support.

4
Successfully Open the Cypress & Click on E2E Testing


5
Create a New Spec file to do Sample Test File


Writing and Executing Your First Cypress API Test

Step 1: Create a Test File

Inside the cypress/e2e folder, create a new test file called api_test_spec.js. You can do this using the terminal:

cypress/e2e/api_test_spec.js

Step 2: Write Your First Test

Open the api_test_spec.js file in Visual Studio and write the following test code:

JavaScript
describe("API Testing with Cypress", () => {
    it("GET request - validate status code", () => {
        cy.request(
              "https://jsonplaceholder.typicode.com/posts/1")
            .its("status")
            .should("equal", 200);
    });
});


7

This test sends a GET request to a sample API and checks that the response status code is 200.

Step 3: Run the Test

Save the file and run the test in the Cypress Test Runner that opened when you ran npx cypress open.

If Cypress is not open, you can run it again using:

npx cypress open

Click on the api_test_spec.js test file in the Cypress Test Runner to execute the test. You should see the test run successfully.

Syntax

Making HTTP Requests with Cypress

Cypress makes it easy to work with different HTTP methods. Here’s how you can perform basic operations:

GET Request:

JavaScript
cy.request("GET",
           "https://jsonplaceholder.typicode.com/posts/1")
    .then((response) => {
        expect(response.status).to.eq(200);
        expect(response.body).to.have.property("id", 1);
    });

POST Request:

JavaScript
cy.request("POST",
           "https://jsonplaceholder.typicode.com/posts",
           {title : "foo", body : "bar", userId : 1})
    .then((response) => {
        expect(response.status).to.eq(201);
        expect(response.body)
            .to.have.property("title", "foo");
    });

PUT Request:

JavaScript
cy.request(
      "PUT", "https://jsonplaceholder.typicode.com/posts/1",
      {id : 1, title : "foo", body : "bar", userId : 1})
    .then((response) => {
        expect(response.status).to.eq(200);
        expect(response.body)
            .to.have.property("title", "foo");
    });

DELETE Request:

JavaScript
cy.request("DELETE",
           "https://jsonplaceholder.typicode.com/posts/1")
    .then((response) => {
        expect(response.status).to.eq(200);
    });


All the requests:

JavaScript
describe('API Testing with Cypress', () => {

    it('GET request - validate status code', () => {
        cy.request('https://jsonplaceholder.typicode.com/posts/1')
          .its('status')
          .should('equal', 200);
    });

    it('POST request - create a new post', () => {
        cy.request('POST', 'https://jsonplaceholder.typicode.com/posts', {
            title: 'foo',
            body: 'bar',
            userId: 1
        }).then((response) => {
            expect(response.status).to.eq(201);
            expect(response.body).to.have.property('title', 'foo');
        });
    });

    it('PUT request - update a post', () => {
        cy.request('PUT', 'https://jsonplaceholder.typicode.com/posts/1', {
            id: 1,
            title: 'baz',
            body: 'qux',
            userId: 1
        }).then((response) => {
            expect(response.status).to.eq(200);
            expect(response.body).to.have.property('title', 'baz');
        });
    });

    it('DELETE request - delete a post', () => {
        cy.request('DELETE', 'https://jsonplaceholder.typicode.com/posts/1')
          .then((response) => {
              expect(response.status).to.eq(200);
          });
    });

});
6

Assertions in Cypress API Testing

Types of Assertions

Assertions are used to verify that the application under test behaves as expected. In Cypress, you can use built-in assertions to validate API responses:

Status Code:

JavaScript
cy.request("https://jsonplaceholder.typicode.com/posts/1")
    .its("status")
    .should("equal", 200);

Response Body:

JavaScript
cy.request("https://jsonplaceholder.typicode.com/posts/1")
    .its("body")
    .should("include", {id : 1});

Headers:

JavaScript
cy.request("https://jsonplaceholder.typicode.com/posts/1")
    .its("headers")
    .its("content-type")
    .should("include", "application/json");

Advanced Cypress API Testing

Handling Authentication

APIs often require authentication. You can handle this in Cypress by including headers in your requests:

JavaScript
cy.request({
      method : "POST",
      url : "https://api.example.com/authenticate",
      body : {username : "user", password : "pass"}
  }).then((response) => {
    const token = response.body.token;

    cy.request({
          method : "GET",
          url : "https://api.example.com/protected",
          headers : {Authorization : `Bearer ${token}`}
      })
        .then(
            (resp) => { expect(resp.status).to.eq(200); });
});

Chaining Requests

You can chain requests together in Cypress to validate a sequence of API calls:

JavaScript
cy.request("POST",
           "https://jsonplaceholder.typicode.com/posts",
           {title : "foo", body : "bar", userId : 1})
    .then((postResponse) => {
        const postId = postResponse.body.id;

        cy.request(
              "GET",
              `https://jsonplaceholder.typicode.com/posts/${
                  postId}`)
            .its("body")
            .should("have.property", "title", "foo");
    });

Testing Error Responses

You should also test how your API handles error cases:

JavaScript
cy.request({
      method : "GET",
      url :
          "https://jsonplaceholder.typicode.com/invalid-url",
      failOnStatusCode : false
  }).then((response) => {
    expect(response.status).to.eq(404);
});

Best Practices for Cypress API Testing

Organizing Test Files

Keep your tests organized by grouping related tests in separate files or folders. This helps in maintaining clarity and ease of access:

cypress/

e2e/

api_tests/

auth_tests.js

post_tests.js

Data Management

Use fixtures or external files to manage test data, which allows for easier test maintenance and scalability:

JavaScript
cy.fixture("user").then((userData) => {
    cy.request("POST",
               "https://jsonplaceholder.typicode.com/posts",
               userData)
        .then((response) => {
            expect(response.status).to.eq(201);
        });
});

Performance Considerations

Make your tests run efficiently by avoiding redundant requests and reusing data wherever possible. For instance, if a token is required for multiple requests, store it and reuse it.

Real-World Examples of Cypress API Testing

Testing a REST API

Here's a complete example of testing a REST API, including CRUD operations:

JavaScript
describe("REST API Testing with Cypress", () => {
    it("Create a new post", () => {
        cy.request(
              "POST",
              "https://jsonplaceholder.typicode.com/posts",
              {title : "foo", body : "bar", userId : 1})
            .then((response) => {
                expect(response.status).to.eq(201);
                expect(response.body)
                    .to.have.property("id");
            });
    });

    it("Get a post by ID", () => {
        cy.request(
              "GET",
              "https://jsonplaceholder.typicode.com/posts/1")
            .its("body")
            .should("have.property", "id", 1);
    });

    it("Update a post", () => {
        cy.request(
              "PUT",
              "https://jsonplaceholder.typicode.com/posts/1",
              {title : "baz", body : "qux", userId : 1})
            .then((response) => {
                expect(response.status).to.eq(200);
                expect(response.body)
                    .to.have.property("title", "baz");
            });
    });

    it("Delete a post", () => {
        cy.request(
              "DELETE",
              "https://jsonplaceholder.typicode.com/posts/1")
            .then((response) => {
                expect(response.status).to.eq(200);
            });
    });
});

Testing a GraphQL API with Cypress

GraphQL APIs can also be tested using Cypress:

JavaScript
describe("GraphQL API Testing with Cypress", () => {
    it("Fetch user data", () => {
        cy.request({
              method : "POST",
              url : "https://api.example.com/graphql",
              body : {
                  query : `
                    {
                        user(id: "1") {
                            name
                            email
                        }
                    }
                `
              }
          }).then((response) => {
            expect(response.body.data.user)
                .to.have.property("name", "John Doe");
        });
    });
});

Conclusion

Cypress is a powerful tool for API testing, offering a robust set of features to validate API functionality, performance, and security. By following best practices and utilizing Cypress's capabilities, you can ensure that your APIs are reliable and meet the expected standards.


Next Article

Similar Reads