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
-
Installation:
-
Ensure Cypress is installed in your project. If not, you can install it using npm:
npm install cypress --save-dev
-
-
Folder Structure:
- By default, Cypress expects your test files to be in the
cypress/integration
directory.
- By default, Cypress expects your test files to be in the
-
Writing API Tests:
- Create a new test file (
api.spec.js
or any name you prefer) insidecypress/integration
.
- Create a new test file (
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:
-
cy.request()
: Cypress providescy.request()
to make HTTP requests. You can specify the method (GET
,POST
, etc.), URL, request body, headers, etc. -
Assertions: Use standard assertion libraries like
expect
(built into Cypress) or Chai assertions (chai.expect
) to validate the API responses. -
Handling Authentication: In the second test (
should handle authentication
), an example of sending aPOST
request with authentication credentials (username
andpassword
) is shown.