Tosca tester
API testing in Cypress.io
As a software tester, you know that API testing is an integral part of software development. API (Application Programming Interface) is like a bridge between different parts of the software, ensuring their smooth communication. A properly functioning API is important for application integration and performance. Today, we’ll look at how you can effectively test APIs using Cypress.io, a tool that lets you accurately and quickly validate API functionality.
Basic API testing concepts
Before we dive into the practical aspects of API testing with Cypress.io, it’s important to be clear on the basic concepts.
What is an API?
An API is a set of definitions and protocols for creating and integrating applications. It acts as a contract between the information provider and the user, determining what data is needed from the provider and what the user needs from the API.
API vs REST API
In addition to API, we also know the so-called REST API. There are several differences between them.
API:
- Web APIs often require a higher level of security because they are used by a wider range of users with different purposes.
- There is also a difference in protocols, as you can use the web API to communicate with users via HTTP or HTTPS.
- The web API can automatically convert request and response data into various formats including JSON, XML, BSON.
REST API:
- REST APIs are typically designed for internal users and applications and therefore require fewer security protocols.
- All communication within the REST API is only supported over HTTP.
- The REST API only supports the JSON data format and is therefore less flexible.
Read more about REST API testing in this article.
The importance of API testing
API testing is a vital part of integration testing, aimed at verifying that the API meets expectations in functionality, reliability, performance and security. Because of its speed and reliability, API testing is becoming increasingly important in software testing.
API endpoints
API endpoints are entry points in the communication channel where two software applications interact. An endpoint is essentially a server or service that allows the API to access the resources it needs. For example, the API weather – this endpoint could be used for an API that provides weather forecasts. It is used to obtain weather data such as temperature, precipitation and other meteorological information.
Cypress: Why It’s Ideal for API testing
Cypress.io is a modern testing tool that provides users – like you – with a great environment for API testing. Its main advantage is integration with JavaScript and Node.js, which eliminates the need for additional libraries, dependencies or drivers. This tool is especially popular among developers and testers who have become accustomed to JavaScript, as it doesn’t need complicated configuration and is easy to install using the Node Package Manager (NPM).
Our next article with the theme Cypress:
- Reviews on the tool – Cypress Testing
- Test Tuning – Cypress debugging
Test Runner role in Cypress API testing
The Test Runner in Cypress.io is one of the key features that greatly improves the efficiency and convenience of testing. It provides a visual and interactive platform to run, monitor and debug tests in real time.
When testing APIs in Cypress.io, the Test Runner provides several specific benefits that increase the efficiency and accuracy of testing. These benefits are particularly valuable in automation API testing, where fast and accurate validation is important:
1. Detailed view of requests and responses
- Test Runner allows you to see the exact details of each request and response, including methods, status codes, headers and request/response bodies. This is invaluable for quickly diagnosing problems and verifying that the API is responding correctly.
2. Visualization of the test procedure
- It allows you to track the progress of individual tests in real time, making it easier to identify specific steps where a test is failing. Visualization is particularly useful when debugging complex test scenarios.
3. Ability to debug tests in real time
- Cypress Test Runner provides a real-time “debugging” capability, which means you can stop test execution at a specific point and check the status of the application or API responses. Use this when looking for ambiguities or when testing new API endpoints.
4. Historical view of test results
- Test Runner stores the results of previous tests, allowing you to compare current results with previous ones and see how changes in code or APIs are reflected in tests.
5. Integration with CI/CD
- Cypress Test Runner can be integrated within the CI/CD pipeline, enabling automated test execution with each deployment or code update, increasing the reliability of software delivery.
6. Easy test creation and management
- A simple interface allows you to quickly create new tests and manage existing ones. Tests can be organized and run individually or in groups, increasing tester productivity.
7. Understandable error messages
- The error messages in the Test Runner are easy to understand and provide enough information to quickly find and fix problems.
Syntax and usage of .request()
API testing in Cypress.io focuses on the use of the .request() command, which is the basic tool for sending HTTP requests to the API server and receiving responses.
The cy.request() command in Cypress.io allows you to create different types of HTTP requests such as GET, POST, PUT, DELETE and more. This command is extremely flexible and can be used to test a wide range of API functions.
cy.request({
method: 'METHOD', // Napríklad 'GET', 'POST', 'PUT', 'DELETE'
url: 'URL_ENDPOINT', // URL endpointu, na ktorý sa požiadavka odosiela
body: {
// Objekt s dátami, ktoré sa majú odoslať, používa sa hlavne pri POST a PUT
},
headers: {
// Objekt s prípadnými hlavičkami požiadavky
},
auth: {
// Autentifikačné údaje, ak sú potrebné
},
// Môžu byť pridané ďalšie možnosti, ako timeout, cookies atď.
}).then((response) => {
// Spracovanie odpovede
})
Important aspects of Cypress API testing
- Responses and their status codes: verification of responses and their status codes is key. For example, a status code of 200 indicates success, while codes such as 404 or 500 indicate errors.
- Content validation of responses: in addition to status codes, it is important to validate the content of the responses themselves, such as the data returned in the response or specific headers.
- Authentication and authorization: for APIs requiring authentication or authorization, you need to ensure that request() statements contain the appropriate authentication credentials.
Cypress testing for the sample application: the to-do list
If you want to test the API of a specific application, we can use an example of a task management application (To-Do List). This application allows users to create, view, update and delete tasks.
Using this simple example, we can demonstrate the basic approach to API testing in Cypress, where the main goal is to verify that the API responds correctly to requests and returns the expected data.
1. Get Task List (GET)
The goal of the GET request to retrieve the To-Do List in this example test in Cypress will be to verify that the To-Do List API is working properly by returning a complete and up-to-date To-Do List.
it('získa zoznam úloh', () => {
cy.request('GET', '/api/todos').then((response) => {
expect(response.status).to.eq(200); // Overenie, že stavový kód je 200
expect(response.body).to.be.an('array'); // Overenie, že telo odpovede je pole
// Tu môžeš pridať ďalšie overenia podľa štruktúry tvojho API
});
});
The use of then() in Cypress tests allows for asynchronous processing of the response from an API request, ensuring that validations are only performed after the response has been fully received. This approach ensures that the tests are reliable and accurate as they work with complete and up-to-date response data.
expect is used to verify various aspects of this answer. This way you can verify that the status code of the answer matches the expectations (for example, 200 for a successful answer) and that the format and content of the answer are correct (for example, verifying that the answer is a task field).
2. Create New Task (POST)
it('vytvorí novú úlohu', () => {
cy.request('POST', '/api/todos', {
title: 'Nakúpiť potraviny', // Názov úlohy
completed: false, // Stav dokončenia úlohy
description: 'Mlieko, chlieb, jablká' // Detailný popis úlohy
}).then((response) => {
expect(response.status).to.eq(201); // Overenie, že úloha bola úspešne vytvorená
// Tu môžeš pridať ďalšie overenia, napríklad pre kontrolu obsahu v odpovedi
});
});
In this example, a POST request is sent to the /api/todos endpoint, sending an object with a single title property in the request body. After the request is sent, it is verified that the server responded with a 201 code, indicating that the job was successfully created.
3. Update Existing Task (PUT)
it('aktualizuje úlohu nákupu potravín', () => {
cy.request('PUT', '/api/todos/nakup-potravin', {
title: 'Nákup na piknik', // Aktualizovaný názov úlohy
completed: false, // Stav dokončenia úlohy
description: 'Kúpiť hrozno, jahody, chlieb a uhorku' // Aktualizovaný popis úlohy
}).then((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.have.property('title', 'Nákup na piknik');
expect(response.body).to.have.property('completed', false);
expect(response.body).to.have.property('description', 'Kúpiť hrozno, jahody, chlieb a uhorku');
});
});
In this example, in addition to changing the task title, additional parameters such as completed and description are added. These parameters are included in the body of the PUT request. After the request is sent, it is verified that the server has responded with a code of 200 and that all of these attributes are correctly updated in the response from the server.
4. Delete Task (DELETE)
Suppose we want to remove a specific task.
it('odstráni úlohu nákupu potravín', () => {
cy.request('DELETE', '/api/todos/nakup-potravin').then((response) => {
expect(response.status).to.eq(200); // Overenie, že úloha nákupu potravín bola úspešne odstránená
});
});
In this example, a DELETE request is sent to the endpoint /api/todos/buy-food, where buy-food is the ID of the job we want to delete. After the request is sent, it is verified that the server responded with a code 200, indicating that the job was successfully removed.
Cypress-plugin-api
Cypress-plugin-api is a plugin for Cypress that extends its API testing functionality, providing advanced options for handling requests and responses. This plugin makes testing RESTful APIs easier and increases the efficiency and accuracy of tests. For more information and details on using cypress-plugin-api, you can visit its official documentation or the GitHub repository (read our article Git, Github and Gitlab) for installation instructions, configuration and usage examples.
Conclusion
Cypress provides a powerful and flexible tool for testing web applications, including APIs. Cypress also has the advantage of its intuitive interface and a rich community that provides support and regular updates. For best results, it is recommended to take advantage of all the available resources and documentation that Cypress provides, including plugins such as cypress-plugin-api that further extend its capabilities.
If you are an IT tester or IT automation tester, speak German and are looking for a job, check out our employee benefits and respond to our job offers!