DEV Community

Bharath Kumar S
Bharath Kumar S

Posted on • Edited on

2

API Tests with Cypress.IO

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

  1. Install Node.js and npm https://www.npmjs.com/get-npm
  2. Any API you would like to use

Setup

  1. create a directory for the project and cd to it: mkdir cypress-api-automation-tests && cd cypress-api-automation-tests
  2. Run npm init --y to setup a new npm package project.
  3. Install Cypress via npm npm i cypress --save-dev.
  4. Verify Cypress by running npx cypress open.
  5. Now cypress folder along with cypress.json file will be created in the project directory.
  6. "integration" folder contains cypress test examples.
  7. Edit the "cypress.json" file to add baseURL for all the tests
{
"baseUrl": "https://jsonplaceholder.typicode.com/"
}
Enter fullscreen mode Exit fullscreen mode

Creating and Run Tests

  1. 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);
        })
     })
 })
Enter fullscreen mode Exit fullscreen mode

2.In Cypress, run the test and notice the results.

image

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"
  }
Enter fullscreen mode Exit fullscreen mode

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)
                }
            })
    })
})
Enter fullscreen mode Exit fullscreen mode

result will be

image

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"
          }
Enter fullscreen mode Exit fullscreen mode

image

Ignore the examples folder by adding as ignored test is cypress.json

{
    "baseUrl": "https://jsonplaceholder.typicode.com/",
    "ignoreTestFiles": "**/examples/*.js"
}
Enter fullscreen mode Exit fullscreen mode

Git repo : https://github.com/Bharath-Kumar-S/cypress-api-automation-tests

I hope this was helpful. Please leave your feedback.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (2)

Collapse
 
craigeddy profile image
Craig R. Eddy

I followed the instructions, but in step 7 had to use:

{
"baseUrl": "https://jsonplaceholder.typicode.com/"
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rebaiahmed profile image
Ahmed Rebai

Nice blog

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay