Rest API Testing with Cypress

Strategies for Self Learning Systems

I already explained in a previous blog post why API Testing matters more than GUI testing. While there are various tools available for API testing, Cypress can test API’s too.

Why Cypress for REST API Testing?

Cypress is an end-to-end testing framework for web applications. However, many people are unaware that it can also handle API testing efficiently. Here are a few reasons why Cypress is a great choice for REST API testing:

  • JavaScript-based: Cypress is built using JavaScript, which makes it easy to use for developers who are already familiar with the language. You can write your API tests in JavaScript, leveraging its flexibility and extensive ecosystem.
  • Powerful testing capabilities: Cypress provides a wide range of features and utilities that enable you to write comprehensive and robust API tests. It supports making HTTP requests, handling responses, and performing assertions to validate the expected behavior of your API endpoints.
  • Real-time debugging: Cypress offers a unique feature called “time-travel debugging.” It allows you to pause your test execution at any point and inspect the state of your application, including network requests and responses. This feature can be incredibly helpful when debugging API issues.
  • Easy setup: Setting up a Cypress project is straightforward. With just a few simple steps, you can have a test environment ready for writing and executing API tests.

Setting up the Test Environment:

Let’s dive into the steps to set up the test environment for REST API testing with Cypress:

Install Cypress

Begin by installing Cypress as a dev dependency in your project. Open your terminal and run the following command:

npm install cypress --save-dev

Initialize Cypress

Once the installation is complete, initialize Cypress by running the following command:

npm run cypress open

This command will create the necessary folder structure and files for Cypress within your project directory.

Write some Test Cases

Create a Test File

In the cypress/e2e directory, create a new test file specifically for API tests. For example, you can name it api.cy.js.

Write API Test Cases

Open the api.cy.js file and start writing your API test cases using the Cypress API commands. Utilize the cy.request() command to make API calls and validate responses.

For instance, you can write a simple test case to validate the status code and response body of an API endpoint:

describe('API Tests', () => {
  it('should return a valid response', () => {
    cy.request('GET', '/api/endpoint/ping')
      .then((response) => {
        expect(response.status).to.eq(200);
        expect(response.body).to.eq('pong');
      });
  });
});

Customize API Requests

To customize API requests, you can specify headers, query parameters, request bodies, and more. Cypress allows you to tailor each request to your specific needs. Here’s an example of a customized API request that sends extra headers with the POST call:

cy.request({
  method: 'POST',
  url: '/api/endpoint',
  headers: {
	'Accept': 'application/json',
    'Authorization': 'Bearer <token>',
  },
  body: {
    key1: 'value1',
    key2: 'value2',
  },
});

It is possible to add query parameters:

cy.request({
	method: 'GET',
	url: '/api/endpoint',
	qs: {
		param: 'true'
	},
	headers: {
		accept: 'application/json'
	}
})

Get data from the request

After a request receives a response from the server, you can access the information using the .then() command.

cy.request({
  method: 'POST', 
  url: '/api/endpoint', 
  body: {
    name: 'this is my post body content'
  }
}).then( (reply) => {
  console.log(reply.status) // 201
  console.log(reply.body) 
})

This will log the status and body of the reply on the console.

Check for response data

Now we can see if the response data in the body is correct. Cypress has chai library bundled with it, so we can make use of it.

cy.request({
  method: 'POST', 
  url: '/api/endpoint', 
  body: {
    name: 'this is my post body content'
  }
}).then( (reply) => {
    expect(reply.status).to.eq(200);
    // We receive an array of 2 items
    expect(response.body).to.have.length(2);
    expect(response.body[0].name).to.eq('the name of first element');
})

Alias can be skipped

The reply alias in the .then function can be skipped if you use destructuring.

cy.request({
  method: 'POST', 
  url: '/api/endpoint', 
  body: {
    name: 'this is my post body content'
  }
}).then( ({body}) => {
    expect(body).to.have.length(2);
    expect(body[0].name).to.eq('the name of first element');
})

Run API Tests

You have two options for running your API tests. You can either use the Cypress Test Runner or run tests from the command line.

To use the Test Runner, open Cypress by running npm run cypress open. From the Test Runner interface, select your API test file (api.cy.js) and click to run it.

To run tests from the command line, use the following command:

npm run cypress run

Conclusion

Cypress offers a seamless and efficient approach to REST API testing. Its architecture, combined with its powerful API commands and easy setup, makes it an excellent choice for API testing.

Happy testing!

References