What is Cypress?
Cypress is a next generation front end testing tool built for the modern web. Learn about Cypress.io and its features.
Pre-requisites
- Install Node.js and npm https://www.npmjs.com/get-npm
- Any API you would like to use
Setup
- create a directory for the project and cd to it:
mkdir cypress-api-automation-tests && cd cypress-api-automation-tests
- Run
npm init --y
to setup a new npm package project. - Install Cypress via npm
npm i cypress --save-dev
. - Verify Cypress by running
npx cypress open
. - Now cypress folder along with cypress.json file will be created in the project directory.
- "integration" folder contains cypress test examples.
- Edit the "cypress.json" file to add baseURL for all the tests
{
"baseUrl": "https://jsonplaceholder.typicode.com/"
}
Creating and Run Tests
- Under the “integration” folder create a new file. Name it “typicode-api-test.js”
/// <reference types="cypress" />
describe('JSON Typicode', () => {
it('Get all user posts', () => {
cy.request('/posts')
.then((response) => {
expect(response.status).to.equal(200);
})
})
})
2.In Cypress, run the test and notice the results.
Try to assert on few other other objects returned in the response and verify it’s working properly.
Example Assertions
Check for available keys in the response object.
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
We need to check if userId, id, title and body keys are present in the response object.
/// <reference types="cypress" />
describe('JSON Typicode', () => {
it('Get all user posts', () => {
cy.request('/posts')
.then((response) => {
let first_response_object = Object.keys(response.body[0]);
let keys = [`userId`, `id`, `title`, `body`];
for (let key of keys) {
expect(first_response_object).to.includes(key)
}
})
})
})
result will be
Note
- Object.keys(object) will return array of available keys.
- And we iterate over the keys array and asserted with includes method.
Post a new user post.
request body will be the following
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Ignore the examples folder by adding as ignored test is cypress.json
{
"baseUrl": "https://jsonplaceholder.typicode.com/",
"ignoreTestFiles": "**/examples/*.js"
}
Git repo : https://github.com/Bharath-Kumar-S/cypress-api-automation-tests
I hope this was helpful. Please leave your feedback.
Top comments (2)
I followed the instructions, but in step 7 had to use:
Nice blog