0% found this document useful (0 votes)
128 views23 pages

Cypress API AutomationV1.0 2023

The document discusses Cypress API automation testing. It introduces Cypress and its features for API testing. It describes different HTTP methods used in APIs like GET, POST, PUT, PATCH, DELETE and provides examples of their status codes and body data requirements. It also covers basics of setting up Cypress for API testing including installation, folder structure, scripts structure and different types of authentications that can be used.

Uploaded by

mohan S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views23 pages

Cypress API AutomationV1.0 2023

The document discusses Cypress API automation testing. It introduces Cypress and its features for API testing. It describes different HTTP methods used in APIs like GET, POST, PUT, PATCH, DELETE and provides examples of their status codes and body data requirements. It also covers basics of setting up Cypress for API testing including installation, folder structure, scripts structure and different types of authentications that can be used.

Uploaded by

mohan S
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

2023

CYPRESS API AUTOMATION

MOHAN SEERANGAN
9/9/2023
Contents
1. Cypress API Automation – Introduction ......................................................................................................... 3
1. Introduction of Cypress API Testing ............................................................................................................ 3
2. Different types of methods in API............................................................................................................... 3
3. Basics of Cypress API Testing ...................................................................................................................... 4
4. Features of Cypress API testing................................................................................................................... 5
5. Why asynchronous is used in JavaScript? ................................................................................................... 6
6. What is Cypress Asynchronous Behaviour? ................................................................................................ 6
2. Node JS ............................................................................................................................................................ 6
1. What is node.JS ........................................................................................................................................... 6
2. Main Features of Node JS: .......................................................................................................................... 7
3. Why Do We Use NodeJs? ............................................................................................................................ 7
4. Features of NodeJs ...................................................................................................................................... 7
5. Node.js Architecture ................................................................................................................................... 8
7. Cypress API Automation.................................................................................................................................. 9
1. Prerequisite - Setting up Cypress Environment .......................................................................................... 9
2. Folder Structure for cypress API ............................................................................................................... 10
3. Scripts Structure for Cypress ..................................................................................................................... 11
4. Different types of authentications ............................................................................................................ 12
5. Cypress API json schema validation .......................................................................................................... 13
5. Cypress API xml schema validation ........................................................................................................... 14
6. Configuration of Client Certificate ............................................................................................................ 15
7. Hooks in Cypress ....................................................................................................................................... 16
8. Cypress API Form data .............................................................................................................................. 17
9. Data parameterization for Cypress API using csv file ............................................................................... 18
10. API Chaining in Cypress ......................................................................................................................... 19
11. Nested API Chaining in Cypress............................................................................................................. 19
12. Read and Write data from the files....................................................................................................... 19
13. Asynchronous in cypress API................................................................................................................. 19
8. Cypress API Integration ................................................................................................................................. 19
1. CI/CD configuration of Cypress API using Jenkins pipeline Steps ............................................................. 19
2. CI/CD configuration of Cypress API with Jenkins pipeline using java scripts ............................................ 20
9. Cypress API Automation – Real time Concepts............................................................................................. 22
1. Best practice for Cypress API testing ........................................................................................................ 22
2. Challenges for cypress API Automation using java scripts ........................................................................ 23

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 2


1. Cypress API Automation – Introduction
1. Introduction of Cypress API Testing
1. What is Cypress?
Cypress is a popular end-to-end testing framework for web applications, but it can also be used for API
testing. API testing with Cypress allows you to test the interactions between your application and external
services or APIs. Cypress is a Test Automation Tool that can test anything that runs on a web browser using
Java Scripts. This is not using Selenium. Cypress is Open source, and this enables you to write faster, easier
and more reliable tests compare to other automation tool. All the document available in cypress.io website.
It will support the below languages,
1. Java scripts
2. Type scripts
2. How to use Cypress?
✓ Setup tests
✓ Write tests
✓ Run tests
✓ Debug
3. Bowser supports?
✓ Chrome
✓ Firefox
✓ Edge
✓ Electron
✓ Brave
4. Who uses Cypress?
Cypress enables you to write all types of tests,
• End-to-end tests
• Integration tests
• Component tests
• Unit tests
Cypress can test anything that runs in a browser.

2. Different types of methods in API


1) GET:
▪ Status Codes: 200 OK (successful), 404 Not Found (resource not found), 401 Unauthorized
(authentication required).
▪ Body Data: Typically, GET requests do not include a request body. They may include query parameters
for filtering data.
2) POST:
▪ Status Codes: 201 Created (resource successfully created), 400 Bad Request (invalid input data), 401
Unauthorized (authentication required).
▪ Body Data: POST requests often include data in the request body, typically in JSON or form-encoded
format, to create a new resource on the server.
3) PUT:
▪ Status Codes: 200 OK (resource updated), 201 Created (resource created if it didn't exist), 204 No
Content (no response body, but resource updated), 401 Unauthorized (authentication required).
▪ Body Data: PUT requests are used to update an existing resource. They include the updated data in the
request body.
4) PATCH:

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 3


▪ Status Codes: 200 OK (partial update successful), 204 No Content (no response body, but update
successful), 401 Unauthorized (authentication required).
▪ Body Data: PATCH requests update a portion of an existing resource. They include only the changed data
in the request body.
5) DELETE:
▪ Status Codes: 204 No Content (resource successfully deleted), 404 Not Found (resource not found), 401
Unauthorized (authentication required).
▪ Body Data: DELETE requests may not include a request body, or they can include data to specify which
resource to delete.
6) HEAD:
▪ Status Codes: 200 OK (resource exists), 404 Not Found (resource not found).
▪ Body Data: HEAD requests are similar to GET but do not include a response body. They are used to check
the existence of a resource.
7) OPTIONS:
▪ Status Codes: 200 OK (server supports the requested methods), 404 Not Found (resource not found).
▪ Body Data: OPTIONS requests do not usually include a request body. They are used to retrieve
information about the communication options for the target resource.
8) Custom Methods:
▪ You can define custom HTTP methods in your API, and their status codes and body data requirements
would depend on how your API is designed.

Remember that the specific status codes and body data requirements can vary depending on the API's design
and implementation. Always refer to the API documentation or specification provided by the service you are
testing for accurate details on how to use these methods and their expected responses.

Methods Body data Status Code Status Text


GET No body 200 OK
POST Body 201 Created
PUT Body 200 OK
PATCH Body 200 OK
DELETE No body 204 No Content

3. Basics of Cypress API Testing


1. Installation: First, you need to install Cypress and set up a project. You can do this using npm or yarn:
npm install cypress --save-dev

2. Creating Tests: Create a test file (e.g., api.spec.js) to write your API tests. You can organize your tests into
describe/it blocks, just like in traditional Cypress end-to-end tests.

3. Making API Requests: To make API requests, you can use the cy.request() command. It allows you to send
HTTP requests like GET, POST, PUT, DELETE, etc., to your API endpoints.

cy.request({
method: 'GET',
url: 'https://api.example.com/resource',
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
},
}).as('getResponse');

4. Assertions: After making a request, you can use Cypress assertions to verify the response. You can check for
status codes, response body content, headers, and more.
Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 4
cy.get('@getResponse').should((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.have.property('data');
expect(response.headers).to.have.property('content-type', 'application/json; charset=utf-8');
});

5. Hooks and Aliases: Cypress allows you to use aliases to store and reuse elements or responses in your tests.
This is useful for making assertions and performing actions based on previous results.

cy.request(...).as('getResponse');
cy.get('@getResponse').then((response) => {
// Use the response data in your test
});

4. Features of Cypress API testing


Cypress is primarily known for end-to-end (E2E) testing of web applications, and it excels in that area. While it
wasn't originally designed for API testing, it can certainly be used for that purpose, thanks to its flexibility and
powerful capabilities. Here are some features of Cypress that are useful for API testing:

1. JavaScript Testing: Cypress uses JavaScript for writing tests, which is widely known and used by developers.
This makes it easy to get started with Cypress for API testing.
2. HTTP Requests: Cypress can make HTTP requests (GET, POST, PUT, DELETE, etc.) to interact with APIs and
web services.
3. Chaining Commands: Cypress allows you to chain commands, which makes it easy to build complex API
testing scenarios step by step.
4. Real-Time Reload: Cypress provides real-time reloading of your test code as you make changes. You can
instantly see the results of your API tests as you modify your code.
5. Fixtures: You can use fixtures to store and load sample data for API requests and responses, making your
tests more dynamic and data-driven.
6. Assertions: Cypress provides a wide range of built-in assertions that you can use to validate API responses
and other aspects of your application's behavior.
7. Automatic Waiting: Cypress automatically waits for elements or API requests to be ready before interacting
with them, eliminating the need for explicit waits or sleeps in your tests.
8. Debugging Tools: Cypress comes with a built-in debugger that allows you to pause and inspect the state of
your test at any point in its execution.
9. Time-Travel Debugging: Cypress allows you to time-travel through your test, letting you step backward and
forward to see what your application looked like at different points in time.
10. Cross-Browser Testing: While originally focused on Chrome, Cypress has expanded its browser support to
include other browsers, allowing you to run API tests in different environments.
11. Data Parameterization: While Cypress does not have built-in support for data parameterization, you can
implement it manually by reading data from external sources like CSV files or JSON files.
12. Cypress Commands: You can extend Cypress with custom commands to encapsulate common API testing
tasks and make your tests more readable and maintainable.
13. Plugins and Libraries: Cypress has an active community that has developed plugins and libraries to extend
its capabilities. There are libraries like cy-api that make API testing in Cypress more convenient.
14. Parallel Testing: Cypress supports parallel test execution, allowing you to run multiple API tests
concurrently, speeding up your test suite.
15. Integration with CI/CD: You can easily integrate Cypress with continuous integration and continuous
deployment (CI/CD) pipelines to automate API testing as part of your development workflow.
16. Mocking and Stubs: Cypress allows you to stub or mock API responses, enabling you to isolate your API tests
from external dependencies.

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 5


17. Command Line Interface: Cypress provides a command-line interface (CLI) that makes it easy to run tests
from the terminal or in CI/CD pipelines.
18. Video and Screenshot Capture: Cypress can capture videos and screenshots of test runs, which is helpful
for debugging and documenting test results.

While Cypress is a versatile tool for API testing, it's worth noting that it's primarily designed for front-end testing.
For more complex API testing scenarios or if you need to work extensively with XML or other data formats, you
may want to consider dedicated API testing tools like Postman or REST Assured. However, for teams already
using Cypress for front-end testing, leveraging its capabilities for API testing can be a convenient option.

5. Why asynchronous is used in JavaScript?


Asynchronicity means that if JavaScript has to wait for an operation to complete, it will execute the rest
of the code while waiting. Note that JavaScript is single-threaded. This means that it carries out asynchronous
operations via the callback queue and event loop.

6. What is Cypress Asynchronous Behaviour?


In Cypress framework, the code runs in parallel and waits for each command to complete before moving on
without interfering with the state of the preceding command. Even though we wrote our code sequentially,
asynchronous code runs immediately and is independent of earlier commands.
• Asynchronous JavaScript → Asynchronous is a non-blocking architecture, so the execution of one task
isn't dependent on another. Tasks can run simultaneously.
• Synchronous JavaScript → Synchronous is a blocking architecture, so the execution of each operation is
dependent on the completion of the one before it.
The difference between a client’s synchronous and asynchronous calls to a server is illustrated below.

2. Node JS
1. What is node.JS
1. Node.js is open-source, cross-platform server environment that can run on Windows, Linux, Unix,
macOS, and more.
2. Made for Developing server side and network applications for executing Java script outside of Browser.
3. Node.js is a back-end JavaScript runtime environment, runs on the V8 JavaScript engine, and executes
JavaScript code outside a web browser.
4. NodeJS is not a programming language.
5. NodeJS is not Framework.
6. Node.js is a server-side platform built on Google Chrome's JavaScript Engine (V8 Engine).

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 6


NodeJS = Runtime Environment + JavaScript Library

2. Main Features of Node JS:


Allows to Run JavaScript outside a web browser.

3. Why Do We Use NodeJs?


There are many reasons for which we prefer using NodeJs for the server side of our application, some of them
are discussed in the following:
• NodeJs is built on Google Chrome’s V8 engine, and for this reason its execution time is very fast and
it runs very quickly.
• There are more than 50,000 bundles available in the Node Package Manager and for that reason
developers can import any of the packages any time according to their needed functionality for which
a lot of time is saved.
• As NodeJs do not need to wait for an API to return data , so for building real time and data intensive
web applications, it is very useful. It is totally asynchronous in nature that means it is totally non-
blocking.
• The loading time for an audio or video is reduced by NodeJs because there is better synchronization
of the code between the client and server for having the same code base.
• As NodeJs is open-source and it is nothing but a JavaScript framework , so for the developers who
are already used to JavaScript, for them starting developing their projects with NodeJs is very easy.
4. Features of NodeJs
Now let us discuss on some of the features of NodeJs:
• Asynchronous in Nature and Event driven: All APIs of Node.js library are asynchronous, that is, non-
blocking. It essentially means a Node.js based server never waits for an API to return data. The server
moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server
to get a response from the previous API call.
• Very Fast − Being built on Google Chrome's V8 JavaScript Engine, Node.js library is very fast in code
execution.
• Single Threaded Architecture: With event looping, a single threaded architecture is followed by NodeJs
and for this architecture makes NodeJs more scalable. In contrast to other servers, limited threads are
created by them for processing the requests. Whereas for the event driven mechanism, the NodeJS
servers reply in a non-blocking or an asynchronous manner and for this reason NodeJS becomes more
scalable. If we compare NodeJs with other traditional servers like Apache HTTP servers, then we can say
NodeJs handles a larger number of requests. A single threaded program is followed by NodeJS and this
allows NodeJs to process a huge amount of requests.

• Scalable: Nowadays, scalable software is demanded by most of the companies. One of the most pressing
concerns in Software Development is addressed by NodeJs and that is scalability. Concurrent requests
can be handled very efficiently using NodeJs. A cluster module is used by NodeJs for managing the load
balancing for all the active CPU cores. The most appealing feature of NodeJs is that it can partition the
applications horizontally and this partition procedure is mainly achieved by it due to the use of child
processes. Using this feature, the distinct app versions are provided to the different target audiences
and also for customization it allows them for catering to the client preferences.

• Quick Execution time for code: V8 JavaScript runtime motor is used by NodeJs and this is also used by
Google chrome. A wrapper is provided for the JavaScript by the hub and for that reason the runtime
motor becomes faster and for this reason inside NodeJs, the preposition process of the requests also
become faster.

• Compatibility on the cross platforms: Different types of systems like Windows, UNIX, LINUX, MacOS
and other mobile devices can use NodeJs. For generating a self-sufficient execution, it can be paired with
any appropriate package.

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 7


• Uses JavaScript: From an engineer's perspective, it is a very important aspect of NodeJs that this
framework uses JavaScript Most of the developers are familiar with JavaScript, so for them it becomes
very easier to grab NodeJs.

• Fast Data Streaming: The processing time of the data that have been transmitted to different streams
takes a long time. Whereas for processing the data, NodeJs takes a very short amount of time and it
does it at a very fast rate. NodeJs saves a lot of time because the files are processed and uploaded
simultaneously by NodeJs. So as a result, the overall speed of data and video streaming is improved by
NodeJs.

• No Buffering : The data is never buffered in NodeJs application.

5. Node.js Architecture
Now that we established what is Node, let’s dig into its architecture. Node.js operates on a single-thread,
allowing it to handle thousands of simultaneous event loops. Here’s a diagram, provided by Sinform.com, that
best illustrates Node.js architecture.

Parts of Node.js

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 8


7. Cypress API Automation
1. Prerequisite - Setting up Cypress Environment
1. Cypress Prerequisites and installation
Prerequisites:
1. Windows 7 and above
2. macOS 10.9 and above (64 bits only)
3. Linux Ubuntu 12.04 and above, Fedora 21 and Debian 8 (64 bits only)
Installation:
Step 1: Install Node.js
1. Node JS – 10 or 12 and above – direct download from cypress.io or https://nodejs.org/en/download
and download based on operating systems. Install cypress as per software extension.
2. Check the command prompt after install node JS.
node -v or node --version
npm -v
Step 2: Download Microsoft Visual Studio code and install.

Step 3: Create a new folder for Cypress project.

Step 4: Open the folder in VS code.

Step 5: Open VS code terminal (under view) and run command.


npm init -y //Created the package.json etc

Step 6: Install Cypress and created node_modules


1. Latest version or without Specific version of Cypress
npm install cypress or npm install --save-dev cypress
2. Specific cypress version
npm install [email protected]
3. Created the below folders once installed cypress.
a. node_modules and packages
b. package-lock.json
Step 7: Confirm Cypress version and verify.
npx cypress -v or npx cypress –version

Step 8: Create your API test files in the cypress/integration directory. For example, you can create a file
named api.spec.js. In your API test file, you can use Cypress's cy.request command to make API requests
and write assertions to test the responses.
describe('API Test', () => {
it('should make an API request', () => {
cy.request('GET', 'https://api.example.com/data')
.then((response) => {
// Perform assertions on the response
expect(response.status).to.equal(200);
expect(response.body).to.have.property('data');
});
});
});

Step 9: Open and RUN cypress.


npx cypress open

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 9


Step 10: Browser will open and with E2E Testing and Component testing and select E2E Testing and added
configuration files like 1.cypress.config.js 2. cypress\support\e2e.js 3.cypress\support\commands.js 4.
cypress\fixtures\example.json

Step 11: The list of browsers displayed and select the browser as per your requirements, ‘Start E2E Testing
in <browser>’
Step 12: Select ‘Create new empty spec’ and create filename with extension of cy.js then click ‘create spec’.

Step 13: Extend with Plugins:


You can extend Cypress's API testing capabilities by using plugins like cypress-axios or other custom
commands. These plugins can help you organize your API tests and handle authentication, request/response
logging, and other advanced features.

2. Folder Structure for cypress API


When organizing your Cypress API tests, a well-structured folder layout can help keep your tests organized and
maintainable. Here's a suggested folder structure for Cypress API testing.

cypress-api-framework/
├── cypress/
│ ├── e2e/
│ │ ├── api/
│ │ │ ├── api-spec.js # API test specification file
│ │ │ ├── ...
│ │ ├── ...
│ ├── fixtures/
│ │ ├── example.json # Sample API request/response fixtures
│ │ └── ...
│ ├── support/
│ │ ├── commands.js # Custom Cypress commands (if needed)
│ │ └── e2e.js # Cypress plugins (if needed)
│ └── ...
├── node_modules/ # Node.js modules (created by npm/yarn)
├── cypress.config.json # Cypress configuration file
├── package-lock.json # Lockfile for npm (auto-generated)
├── package.json # Project dependencies and scripts
├── README.md # Project documentation
├── .gitignore # Git ignore file
└── ...

Let's break down the key components of this structure:


▪ cypress/: This is the main directory for your Cypress tests.
o e2e/: The integration folder is where your actual API test files reside.
▪ api/: This subdirectory contains your API test specification files. You can organize
your API tests into multiple files based on the API endpoints or functional areas.
o fixtures/: This directory stores JSON files with sample API request and response payloads.
These fixtures can be used in your tests to simulate API responses.
o support/: Here, you can place custom Cypress commands or utilities that your tests may
require.
▪ commands.js/: It is used to create Custom Cypress commands

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 10


▪ e2e.js/: This directory is used for Cypress plugins, which can extend Cypress's
functionality if needed. You may not always need this folder for API testing.
▪ node_modules/: This directory is created when you install dependencies using npm or yarn. It
contains all the Node.js modules required for your project.
▪ cypress.config.json: The Cypress configuration file contains settings and configurations for your
tests, such as base URLs, browsers, and other options.
▪ package.json: The package.json file lists your project's dependencies, scripts, and other metadata.
You can define custom npm scripts for running your tests and other tasks here.
▪ package-lock.json: This is an auto-generated file that locks the versions of your project's
dependencies to ensure consistency across different environments.
▪ README.md: Your project documentation should go here. Explain how to set up and run the tests,
any prerequisites, and other relevant information.
▪ .gitignore: This file specifies which files and directories should be ignored by Git, ensuring that
generated files and dependencies are not included in version control.

Your API test files in the cypress/integration/api/ directory should follow a naming convention like api-
spec.js and contain your API test cases using Cypress commands for making API requests and assertions.

3. Scripts Structure for Cypress


describe("name", ()=> {
it("name", ()=> {
cy.request (
{
method: "GET",
url: "url",
qs: {page: 2},
body: {
id: 1,
name: "name"
}
headers: {
'content-type': 'application/json; charset=utf-8'
}
auth: {
user: "user",
pass: "pass"
}
cookies: "cookies value"
}
)
.then((response)=>{

//Status details - STATUS CODE


expect(response.stats).to.be.eq(200)
expect(response.stats).to.be.equal(200)
expect(response.stats).to.eq(200)
expect(response.stats).to.equal(200)
expect(response.stats).eq(200)
expect(response.stats).equal(200)

//Status details - STATUS TEXT


expect(response.statusText).eq("OK")
expect(response.statusText).contains("Created")

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 11


//Status details - RESPONSE TIME
expect(response.duration).to.not.be.greaterThan(2000)
expect(response.duration).to.not.be.lessThan(10)

//HEADER - validation
expect(response.headers['content-type']).to.eq('application/json; charset=utf-8')

//Body Single - PROPERTY validations


expect(response).to.have.property('headers')
expect(response).to.has.property('headers')
expect(response).have.property('headers')
expect(response).has.property('headers')

//Body Single- CONTENT validations


expect(response.body).contains('name')
expect(response.body).to.be.eq(1)

//Body Single - PROPERTY + CONTENT validations


expect(response.body).has.property('id', 1)
expect(response.body).has.property('email', '[email protected]')

//Body Array- PROPERTY validations


expect(response.body[0]).to.have.property('headers')
expect(response.body[0]).to.has.property('headers')
expect(response.body[0]).have.property('headers')
expect(response.body[0]).has.property('headers')

//Body Array- CONTENT validations


expect(response.body[0]).contains('name')
expect(response.body[0]).to.be.eq(1)

//Body Array- PROPERTY + CONTENT validations


expect(response.body[0]).has.property('id', 1)
expect(response.body[0]).has.property('email', '[email protected]')

//Body - LENGTH validations


expect(response.body).to.have.length(500)

//LOG - Print
cy.log(JSON.stringify(response));
})
})
})

4. Different types of authentications


Cypress is a popular end-to-end testing framework for web applications, and it doesn't provide built-in
authentication methods for APIs. However, you can use various authentication methods in your Cypress tests to
interact with authenticated APIs. Here are some common methods:

1. Basic Authentication:
You can use the cy.request() command to make API requests with basic authentication by including
the Authorization header with the base64-encoded username and password.
auth: {
username: "yourUsername",

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 12


password: "yourPassword"
}

2. Bearer Token:
If your API uses bearer token authentication, you can include the token in the request headers.
headers: {
Authorization: 'Bearer yourToken'
}

3. OAuth2:
For OAuth2 authentication, you may need to use external libraries or tools to obtain tokens and then include
them in your Cypress tests.
4. API Key:
If your API uses an API key for authentication, you can include it in the request headers.
headers: {
'X-API-Key': 'yourAPIKey'
}
5. Digest Authentication with username password
auth: {
username: "postman",
password: "password",
method: "degest"
}
Remember to securely manage any sensitive information, such as passwords or tokens, in your Cypress test
code. You may want to use environment variables or other secure methods for storing and retrieving these
credentials.

5. Cypress API json schema validation


To perform JSON schema validation in Cypress for API responses, you can use the cy.request command in
combination with a JSON schema validation library such as ajv. Here's a step-by-step guide on how to do it:

1. Install JSON Schema Validation Library (ajv):


You need to install the ajv library to perform JSON schema validation. You can do this using npm or yarn:
npm install ajv --save-dev

2. Create a JSON Schema:


Create a JSON schema that defines the expected structure of the API response. You can define this schema in a
separate .json file, for example, response-schema.json.
{
"type": "object",
"properties": {
"key1": { "type": "string" },
"key2": { "type": "number" }
},
"required": ["key1", "key2"]
}

3. Write Cypress Test:


In your Cypress test, use the cy.request command to send the API request, and then validate the response
against the JSON schema using ajv. Here's an example test:
const Ajv = require('ajv');
const schema = require('./response-schema.json'); // Load your JSON schema

describe('API Response Validation', () => {

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 13


it('should validate the response against the JSON schema', () => {
cy.request({
method:'GET',
url: 'https://example.com/api/endpoint'
})
.then((response) => {
const avjValiadate = new Ajv();
const validate = avjValiadate.compile(schema)
const isvalid = validate(respone.body)
expect(isvalid).to.be.true;
}
});
});
});

4. Run the Cypress Test:


Run your Cypress test by using the Cypress CLI:
npx cypress run

Cypress will execute the test, and if the response does not match the defined JSON schema, it will fail the test
and provide details about the validation error.
This approach allows you to perform JSON schema validation on API responses within your Cypress tests.

5. Cypress API xml schema validation


Cypress primarily focuses on testing web applications and is more geared towards working with web pages and
APIs that return JSON data. While you can use Cypress to send HTTP requests to APIs that return XML responses,
performing XML schema validation directly within Cypress may require additional setup and custom code.

To perform XML schema validation in Cypress for API testing, you'll need to follow these general steps:

1) Install Dependencies:
Install the necessary dependencies for working with XML in Cypress:
npm install xml2js --save-dev -- Here xml2js is a library for parsing XML data.

2) Write the Test:


Write your API test, including the XML schema validation. Here's an example test that makes an API request and
validates the response against an XML schema:

const xml2js = require('xml2js');


const parser = new xml2js.Parser({ explicitArray: false });

describe("XML Parser", ()=> {


const xmlPayload=
"<Pet><id>0</id><Category><id>0</id><name>Dog</name></Category><name>Jimmy</name><phot
oUrls><photoUrl>string</photoUrl></photoUrls><tags><Tag><id>0</id><name>string</name></Tag>
</tags><status>available</status></Pet>"
let petid=null;

it("Creating new PET", ()=> {


cy.request({
method: 'POST',
url: 'https://petstore.swagger.io/v2/pet',

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 14


body: xmlPayload,
headers:
{
'Content-Type': "application/xml",
'accept': 'application/xml'
}
})
.then(response => {
expect(response.status).to.eq(200);
parser.parseString(response.body, (err, result) => {
petid=result.Pet.id
})
})
})

3) Run the Test:


You can run your Cypress tests using the Cypress Test Runner:
npx cypress open

6. Configuration of Client Certificate


1. Store Certificates in Cypress Fixture:
Store your client certificate and private key as fixtures in Cypress. Create a directory named fixtures in your
Cypress project and place your certificate files (client.crt and client.key) in this directory.
cypress/
fixtures/
client.crt
client.key
integration/

2. Update Cypress Test:


In your Cypress test file (your_api_test.spec.js), you'll need to read these fixtures and configure the requests
with the client certificate.
javascript
describe('API Test with Client Certificate', () => {
beforeEach(() => {
cy.visit('your_api_endpoint_url', {
headers: {
'Content-Type': 'application/json',
},
// Load client certificate and key from fixtures
cert: {
key: 'client.key',
cert: 'client.crt',
},
});
});

it('should make an authenticated API request', () => {


// Your API test code here
cy.request({
method: 'GET',
url: '/api/endpoint',

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 15


// Additional request configuration
}).then((response) => {
// Assertions and validations
});
});
});

Replace 'your_api_endpoint_url' with the actual URL of your API endpoint, and customize the request
configuration as needed.

3. Run Cypress Test:


Execute your Cypress test using the following command:
npx cypress open
This will open the Cypress Test Runner, allowing you to select and run your API test.

By following these steps, you can configure client certificate authentication for your Cypress API automation
tests using JavaScript. Make sure to adapt the code and paths to your specific project requirements.

7. Hooks in Cypress
In Cypress API automation, "hooks" refer to special functions that allow you to execute code at various points
in your test suite's lifecycle. Hooks enable you to set up and tear down test data, perform setup or cleanup tasks,
or customize the behavior of your tests. These hooks are executed automatically by Cypress at specific points
during test execution. Here are some commonly used hooks in Cypress API automation:
1) before and after Hooks:
before: This hook is executed once, before any test case in the current suite.
after: This hook is executed once, after all test cases in the current suite have finished.
before(() => {
// Perform setup tasks before any tests in this suite
});

after(() => {
// Perform cleanup tasks after all tests in this suite
});

2) beforeEach and afterEach Hooks:


beforeEach: This hook is executed before each test case in the current suite.
afterEach: This hook is executed after each test case in the current suite.

beforeEach(() => {
// Perform setup tasks before any tests in this suite
});

afterEach(() => {
// Perform cleanup tasks after all tests in this suite
});

3) beforeAll and afterAll Hooks:


beforeAll: This hook is executed once, before any test case in the entire test suite (all suites combined).
afterAll: This hook is executed once, after all test cases in the entire test suite have finished.
beforeAll(() => {
// Perform setup tasks before any tests in this suite
});

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 16


afterAll(() => {
// Perform cleanup tasks after all tests in this suite
});

These hooks allow you to perform actions like setting up a test environment, initializing test data, or cleaning up
resources after tests.

8. Cypress API Form data


In Cypress, you can upload form data in API testing by sending a POST request with the form data included in
the request body. Here's a step-by-step guide on how to do this:

4) Install Dependencies:
Ensure you have Cypress and any necessary plugins or libraries installed. If you haven't already installed Cypress,
you can do so with the following command:
npm install --save-dev cypress

5) Write the Test:


In your Cypress test file, write a test that sends a POST request with form data. Here's an example test:
describe("File Upload", () => {
it("01.Upload image file", () => {
cy.fixture('Upload_Image.png', 'binary').then((file) => {
const blob = Cypress.Blob.binaryStringToBlob(file, 'image/png')
const formData = new FormData()
formData.set("file", blob)

cy.request({
method: 'POST',
url: 'https://api.escuelajs.co/api/v1/files/upload',
body: formData
}).then((response) => {
expect(response.status).to.equal(201);
})
})
})
In this example, we're using the FormData API to create a form data object and append key-value pairs to it.
Then, we send a POST request with this form data as the request body. Make sure to adjust the URL and form
data fields to match your API endpoint and form structure.

6) Run the Test:


You can run your Cypress tests using the Cypress Test Runner:
npx cypress open
Select your test file from the Cypress Test Runner interface, and it will execute the test, uploading form data to
your API.

7) Assertions and Validation:


After sending the request, you can add assertions to validate the response as needed. In the example above,
we're checking if the response status is 201 and if the response body contains a specific message.

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 17


9. Data parameterization for Cypress API using csv file
Parameterizing data in Cypress API tests using a CSV file allows you to run the same test with different sets of
data, making your tests more versatile and efficient. To achieve data parameterization with Cypress API tests
and a CSV file, follow these steps:

1) Prepare Your CSV File:


Create a CSV file containing the test data. Each row should represent a different set of data, and each column
should correspond to a parameter you want to use in your API test. For example:
S.No,Company,Contact,Country
1,Alfreds Futterkiste,Maria Anders,Germany
2,Centro comercial Moctezuma,Francisco Chang,Mexico
3,Ernst Handel,Roland Mendel,Austria
Save this file as testdata.csv in your project directory.

2) Install Dependencies:
You'll need a library to parse CSV files. You can use the csv-parser package. Install it using npm:
npm install neat-csv@v5 --save-dev

3) Write Your Cypress Test:


Create or modify your Cypress test to read data from the CSV file and use it in your API tests. Here's an example:

const neatCSV = require('neat-csv');

describe("Read data from csv", ()=> {

let table;
it("CSV data read", ()=> {
cy
.fixture('Parameterization.csv').then(neatCSV).then(data=> { //Convert csv file into an object
table = data;
})
.then(console.table)
.then(table => {
table.forEach(element => {
cy.log('table : ',table);
})
})
})
it("Print the value", ()=> {
table.forEach(element => {

});
})
})

4) Run the Test:


Run your Cypress test as usual using the Cypress Test Runner:
npx cypress open

Cypress will execute the test for each row in the CSV file, using different data sets for each API request.

With this approach, you can easily parameterize your Cypress API tests using data from a CSV file. It allows you
to test various scenarios and inputs without modifying the test code, making your tests more robust and
maintainable.

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 18


10. API Chaining in Cypress

11. Nested API Chaining in Cypress

12. Read and Write data from the files.

13. Asynchronous in cypress API

8. Cypress API Integration


1. CI/CD configuration of Cypress API using Jenkins pipeline Steps
To set up a CI/CD pipeline for Cypress API testing using Jenkins, you'll need to create a Jenkins pipeline script
(usually written in Groovy) to define the build and deployment steps. Below are the steps to configure a Jenkins
pipeline for Cypress API testing:

Step 1: Set Up Jenkins


Make sure you have Jenkins installed and running. You'll also need to install the following plugins if they're not
already installed:
• Pipeline
• NodeJS
• GitHub Integration (if using GitHub for version control)

Step 2: Create a Jenkinsfile


In your project repository, create a Jenkinsfile (no file extension) at the root. This file defines the Jenkins pipeline
stages and steps. Here's an example Jenkinsfile for Cypress API testing:

groovyCopy code:
pipeline {
agent any

environment {
// Define environment variables, e.g., API_KEY, API_URL
API_KEY = credentials('your-api-key-credential-id')
API_URL = 'https://api.example.com'
}

stages {
stage('Checkout') {
steps {
checkout scm
}
}

stage('Install Dependencies') {
steps {
script {
// Set up Node.js environment
def nodejsInstallation = tool name: 'NodeJS', type: 'NodeJS'
def nodejsHome = toolenv(nodejsInstallation)

// Install dependencies

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 19


sh "npm ci"
}
}
}

stage('Run Cypress API Tests') {


steps {
script {
// Run Cypress API tests
sh "npx cypress run --config baseUrl=${API_URL} --env apiKey=${API_KEY}"
}
}
}
}

post {
success {
// Add post-build actions, e.g., notifications or deployment
}
}
}
This Jenkinsfile defines three stages: checkout, install dependencies, and run Cypress API tests. Make sure to
replace 'your-api-key-credential-id' with the actual Jenkins credential ID for your API key.

Step 3: Set Up Jenkins Credentials


Go to Jenkins > Manage Jenkins > Manage Credentials and add credentials for your API key. This step is necessary
to securely store sensitive information.

Step 4: Configure Jenkins Job


Create a Jenkins job and link it to your project's repository. In the job configuration, specify the location of your
Jenkinsfile within the repository (e.g., "Pipeline script from SCM").

Step 5: Trigger the Jenkins Job


Push changes to your repository, or you can manually trigger the Jenkins job to initiate the pipeline.

Step 6: Monitor Results


Monitor the Jenkins job's console output to see the progress of your Cypress API tests. You can also set up post-
build actions for notifications, artifact archiving, or deployment as needed.

This Jenkins pipeline script will automate the execution of your Cypress API tests whenever changes are pushed
to the repository or when manually triggered. Make sure to adjust the pipeline stages and environment variables
to match your specific project requirements.

2. CI/CD configuration of Cypress API with Jenkins pipeline using java scripts
To set up Continuous Integration and Continuous Deployment (CI/CD) for Cypress API testing using Jenkins
pipeline with JavaScript-based configuration (Jenkinsfile), you can use the Jenkins declarative pipeline syntax.
Below is an example Jenkinsfile for Cypress API testing using JavaScript:

JavaScript:
pipeline {
agent any

stages {
stage('Checkout') {
steps {
Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 20
// Check out your Git repository
git 'https://github.com/your/repo.git'
}
}

stage('Install Dependencies') {
steps {
// Install Node.js and npm (if not already installed)
sh 'curl -sL https://deb.nodesource.com/setup_14.x | bash -'
sh 'apt-get install -y nodejs'
sh 'npm install'

// Install Cypress globally (optional)


sh 'npm install -g cypress'
}
}

stage('Run Cypress API Tests') {


steps {
// Run Cypress API tests
sh 'npx cypress run --config-file cypress-api.json'
}
}
}

post {
success {
// Optional: Trigger deployment or notifications on success
// Example: sh 'deploy.sh' or sh 'send_notification.sh'
}

failure {
// Optional: Trigger notifications or actions on failure
// Example: sh 'send_failure_notification.sh'
}
}
}

In this Jenkinsfile:
1. We define a Jenkins pipeline using JavaScript-based configuration.
2. The pipeline runs on any available agent (agent any).
3. The pipeline consists of three stages: Checkout, Install Dependencies, and Run Cypress API Tests. Customize
these stages based on your project's requirements.
4. In the Checkout stage, we use the git step to check out your Git repository containing the Cypress API tests.
Replace the repository URL with your own.
5. In the Install Dependencies stage, we install Node.js and npm (if not already installed), and then install your
project's dependencies. Optionally, you can install Cypress globally.
6. In the Run Cypress API Tests stage, we execute the Cypress API tests using the sh step with the npx cypress run
command and your specific configuration (cypress-api.json).
7. In the post section, you can define actions to be taken on success or failure. For example, you can trigger
deployment or send notifications based on the pipeline's outcome.

Make sure to adjust the commands, paths, and URLs according to your project's needs, and ensure that Jenkins
is properly configured to execute these steps.

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 21


9. Cypress API Automation – Real time Concepts
1. Best practice for Cypress API testing
1. Separate API Tests from UI Tests:
It's a good practice to keep your API tests separate from your UI tests. Organize your project directory structure
so that API tests have their own folder and are not mixed with UI test files.

2. Use Cypress Commands:


Cypress provides custom commands to make API testing easier and more readable. You can use cy.request() to
make API requests. This command returns a promise, so you can handle the response using .then() or
async/await.

Javascript:
cy.request('GET', '/api/resource')
.then((response) => {
// Assertions on the response
});

3. Use Cypress Fixtures:


Cypress allows you to use fixtures to store and load test data. This can make your tests more maintainable and
readable. You can load fixtures into your request like this:

Javascript:
cy.fixture('example.json').then((data) => {
cy.request('POST', '/api/resource', data);
});
4. Assertions:
Use Cypress' built-in assertions to verify the API responses. You can use .should() to make assertions about the
response status, headers, body, and more.

Javascript:
cy.request('/api/resource')
.should((response) => {
expect(response.status).to.eq(200);
expect(response.body).to.have.property('property_name', 'expected_value');
});
5. Environment Configuration:
Create different environment configurations for your API endpoints (e.g., development, staging, production) and
use configuration files or environment variables to manage these settings. This makes it easier to switch
between environments when running your tests.

6. Test Data Management:


Ensure that your API tests have the necessary test data set up before running the tests. You can use fixtures, API
calls, or database seeding to prepare the required data.

7. Test Data Isolation:


Make sure that your API tests don't affect production or shared data. Use a dedicated test environment or
database for running your API tests.

8. Handling Authentication:
If your API requires authentication, handle it properly in your tests. You can use custom headers, tokens, or
other authentication mechanisms.

9. Use Custom Commands:

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 22


Create custom Cypress commands to encapsulate common API testing tasks. This can help keep your test code
clean and maintainable.

10. Error Handling:


Implement error handling in your tests. Expect and handle different error scenarios gracefully, and make sure
your tests fail with informative messages when something goes wrong.

11. Continuous Integration (CI):


Integrate your Cypress API tests into your CI/CD pipeline to ensure that they are run automatically on each code
commit.

12. Documentation:
Document your API tests, including their purpose, dependencies, and any special considerations. This makes it
easier for other team members to understand and maintain the tests.

2. Challenges for cypress API Automation using java scripts


▪ Limited API Testing Support: Cypress is primarily built for UI testing, so its support for API testing is limited
compared to dedicated API testing tools like Postman or tools like Axios for JavaScript-based API testing.
You may need to write more custom code to handle API-specific scenarios.
▪ Cross-Origin Requests: Cypress enforces the same-origin policy, which can make it challenging to test APIs
hosted on different domains or servers. Dealing with CORS (Cross-Origin Resource Sharing) issues can be
tricky, and you might need to use workarounds like stubbing responses.
▪ Asynchronous Operations: JavaScript is inherently asynchronous, and API testing often involves handling
asynchronous operations like making requests and waiting for responses. You'll need to use techniques like
promises, async/await, or Cypress-specific commands to manage asynchronous behavior effectively.
▪ Dynamic Data and Tokens: APIs often require dynamic data, such as authentication tokens or timestamps,
which can change with each request. Managing and generating dynamic data in your tests can be
challenging.
▪ Data Setup and Cleanup: Properly setting up and cleaning up test data for API tests can be complex,
especially if your tests create or modify data in the API. You may need to implement hooks or scripts to
manage data before and after tests.
▪ API Dependency Management: API tests may have dependencies on other APIs or services, and coordinating
these dependencies can be challenging. You may need to set up test doubles, stubs, or mocks to simulate
dependent services.
▪ Rate Limiting and Throttling: Some APIs have rate limiting or throttling mechanisms in place, which can
affect your test execution. You might need to implement logic to respect these rate limits during testing.
▪ Security Concerns: When working with APIs, you may handle sensitive data or need to test security-related
scenarios. Ensuring that your tests handle security concerns appropriately can be challenging.
▪ Test Data Isolation: Ensuring that your API tests don't affect production data or shared resources is crucial.
You'll need to set up separate environments or databases for testing to avoid data contamination.
▪ Test Execution Speed: API tests, like UI tests, can be slower compared to traditional API testing frameworks.
This can be a challenge when you have a large number of API tests or when you need to execute tests quickly.
▪ Reporting and Integration: Integrating Cypress API tests into CI/CD pipelines and generating meaningful
reports can be challenging, as Cypress was primarily designed for UI testing. You may need to use additional
tools or scripts for reporting and integration.
▪ Limited Native Assertions: Cypress provides limited built-in assertions for API testing. You may need to write
custom assertions to validate API responses fully.

Cypress API Automation short Notes Mohan Seerangan ([email protected]) Page 23

You might also like