API Automation Using Cypress : A Comprehensive Guide

feature image for API Automation Cypress blog

What Is Cypress?

Cypress is a free, open-source, locally installed Test Runner and Dashboard Service for recording your tests. It is a front-end and back-end test automation tool built for the next generation of modern web applications. Nowadays for every application we totally depend on backend services and API’s. So this blog will walk you through the basics of API testing using Cypress.

It is useful for developers as well as QA engineers to test real-life applications developed in React.js, Angular.js, Node.js, Vue.js, and other front-end technologies.

Key Features of Cypress:

  • Mocking – By mocking the server response, it has the ability to test edge cases.
  • Time Travel – It takes snapshots as your tests run, allowing users to go back and forth in time during test scenarios.
  • Flake Resistant – It automatically waits for commands and assertions before moving on.
  • Spies, Stubs, and Clocks – It can verify and control the behavior of functions, server responses, or timers.
  • Real-Time Reloads – It automatically reloads whenever you make changes to your tests.
  • Consistent Results – It gives consistent and reliable tests that aren’t flaky.
  • Network Traffic Control – Easily control, stub, and test edge cases without involving your server.
  • Automatic Waiting – It automatically waits for commands and assertions without ever adding waits or sleeps to your tests. No more async hell.
  • Screenshots and Videos – View screenshots taken automatically on failure, or videos of your entire test suite when it has run smoothly.

Basic Constructs of Cypress

Cypress has adopted Mocha’s syntax for the development of test cases, and it uses all the fundamental harnesses that Mocha provides. Below are a few of the main constructs which we majorly use in Cypress test development:

  • describe():  It’s simply a way to group our tests. It takes two arguments, the first is the name of the test group, and the second is a callback function.
  • context(): It’s just an alias for describe().
  • it(): We use it for an individual test case. It takes two arguments, a string explaining what the test should do, and a callback function that contains our actual test.
  • before():  It runs once before all tests in the block.
  • after(): It runs once after all tests in the block.
  • beforeEach(): It runs before each test in the block.
  • afterEach(): It runs after each test in the block.
  • .only(): To run a specified suite or test, append “.only” to the function.
  • .skip(): To skip a specified suite or test, append “.skip()” to the function.

Cypress Project Setup:

1) Install Node.js

2) Download and install Visual Studio

3) Now create a new folder for the Cypress project

4) Open that folder in VS Code

4) Open the terminal in Visual Studio and run the command npm init-y(it will install package.json file)

5) Now install cypress and run the npm install cypress command in the terminal (It will install the lock package.json file)

6) Now open cypress and run command npx cypress open

Good to Read:- API Automation with Rest assured using (Python + BDD)

7) Click on E2E testing and click continue from the configuration file

8) Now u can see a cypress folder under project folder

9) Now choose browser

10) click on start E2E testing and u can see a create a new spec page from where we can create a new spec

11)  Click on Create spec

12) Now click on okay, run the spec

13) now we can view this file under the e2e folder

Good to Read:- Selenium Web Driver with Python and Pytest Framework

Cypress first Test

  1. Create a file under the Cypress folder
  2. At the top mention  // /<reference types=”cypress”/>
  3. Write Test function
  4. Test npx cypress open
describe('AdminLogin', () => {
  it('Verify response admin to login via password successfully', () => {
    cy.request({
      method:'POST' ,
      url: 'https://agileatoz.com/api/v1/login' ,
      body:{ phone_number:"9999999999", password:"Test@123", login_type:"password" },
    }).then((res)=>
    {
      cy.log(JSON.stringify(res.body))
      expect(res).to.have.property('status').to.equal(200)
      expect(res.body).to.have.property('message').to.equal('login successfully')
    })
  })
}

Best Practices for API Testing with Cypress

To ensure that your API tests are reliable, maintainable, and efficient, follow these best practices:

  1. Use Environment Variables: Store sensitive data like API keys, tokens, or base URLs in environment variables.
  2. Mock Responses Where Necessary: If you don’t want to hit the real API every time, mock the API responses using cy.intercept().
  3. Handle Rate Limits: If your API has rate limits, make sure your tests handle them appropriately by adding retries or delays between requests.
  4. Keep Tests Independent: Ensure that each API test is independent of the others so that they can be run in any order without dependency issues.
  5. Focus on Edge Cases: Test both the happy path and edge cases (e.g., invalid inputs, large data sets, rate limiting) to cover all potential scenarios.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top