Home  Cypress   How to test ...

How to test APIs in Cypress

Testing APIs in Cypress involves making HTTP requests and asserting on the responses returned by those requests. Here’s a step-by-step guide on how to test APIs using Cypress:

Setting Up Cypress for API Testing

  1. Installation:

    • Ensure Cypress is installed in your project. If not, you can install it using npm:

      npm install cypress --save-dev
      
  2. Folder Structure:

    • By default, Cypress expects your test files to be in the cypress/integration directory.
  3. Writing API Tests:

    • Create a new test file (api.spec.js or any name you prefer) inside cypress/integration.

Example: Testing a REST API with Cypress

Let’s assume you have a REST API endpoint (https://api.example.com/users) that returns a list of users. You want to test this API using Cypress.

Example Test (cypress/integration/api.spec.js)

describe('API Tests', () => {
  it('should fetch list of users', () => {
    // Send a GET request to the API endpoint
    cy.request('GET', 'https://api.example.com/users')
      .then((response) => {
        // Assert on status code
        expect(response.status).to.eq(200);

        // Assert on response body
        expect(response.body).to.have.length.above(0); // Ensure there are users returned

        // Example: Assert on specific user properties
        expect(response.body[0]).to.have.property('username').that.is.a('string');
        expect(response.body[0]).to.have.property('email').that.matches(/@example\.com$/);
      });
  });

  it('should handle authentication', () => {
    // Send a POST request with authentication credentials
    cy.request({
      method: 'POST',
      url: 'https://api.example.com/login',
      body: {
        username: 'yourusername',
        password: 'yourpassword'
      },
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((response) => {
      // Assert on status code and authentication token
      expect(response.status).to.eq(200);
      expect(response.body).to.have.property('token').that.is.a('string');
    });
  });
});

Explanation:

Published on: Jun 28, 2024, 03:36 AM  
 

Comments

Add your comment