Cypress API AutomationV1.0 2023
Cypress API AutomationV1.0 2023
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
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.
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
});
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.
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.
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).
• 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.
• 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.
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
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 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’.
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
└── ...
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.
//HEADER - validation
expect(response.headers['content-type']).to.eq('application/json; charset=utf-8')
//LOG - Print
cy.log(JSON.stringify(response));
})
})
})
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",
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.
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.
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.
Replace 'your_api_endpoint_url' with the actual URL of your API endpoint, and customize the request
configuration as needed.
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
});
beforeEach(() => {
// Perform setup tasks before any tests in this suite
});
afterEach(() => {
// 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.
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
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.
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
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 => {
});
})
})
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.
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
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.
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'
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.
Javascript:
cy.request('GET', '/api/resource')
.then((response) => {
// Assertions on the response
});
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.
8. Handling Authentication:
If your API requires authentication, handle it properly in your tests. You can use custom headers, tokens, or
other authentication mechanisms.
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.