Cypress & API Testing in 5 Minutes

Cypress is definitely one of the fastest growing web application automation tools in 2020. The capability of the tool is not restricted only to Web Automation, but also to API Testing.

In this article, we will see how Cypress helps us in creating automated API tests rapidly and with very less lines of code & configuration.

NOTE: If you are new to Cypress, I have written a separate article, Cypress 101 which will help you to kick start with this revolutionary tool.

We can achieve operations like GET, POST, PUT, DELETE, PATCH, TRACE, CONNECT, HEAD and many more.

This article is primarily focussed on GET and POST which are very essential for API Testing.

Get started

Let’s create a new folder and call it “cypress-api-tests-demo”.

Open the Terminal (or Windows Prompt) and navigate to the folder. Lets now initialise the project by typing –

npm init

Provide all the necessary details like below –

Now lets install cypress.io. Type the below command –

npm init cypress install --save-dev

Once installed, type the below command –

npx cypress open

This will open the Cypress.io Test Runner. This confirms that the cypress.io is working as expected.

Now, let’s launch the Visual Studio Code (or any of your favourite IDE) and open the cypress-api-tests-demo project from your local drive.

Navigate to cypress → integration folder and create a file called – api.tests.spec.js

Before we write our tests, lets slightly touch base the method we will be using for API testing. In cypress, we have a method called, cy.request() which will be the base for calling the request URL.

Now, lets try a small test in the api.tests.spec.js file to see if we are getting the response as 200. We will assert it using an inbuilt assertion library (Chai).

describe('GET Service Example', ()=>{

    it("Status Code and Header Validation", ()=>{
        
        cy.request("https://jsonplaceholder.typicode.com/posts/").as('res')
        .its('status')
        .should('equal', 200);
    });

});

Let’s execute the test. Go to the Cypress Test Runner we have already opened. 

You will be able to find the test, api.tests.spec.js and click it. 

Voila! You will be able to see that a Chrome browser will be opened and the API test will be executed there like this –

Congratulations! You just executed your first API Test using Cypress.io.

Now, time for us to validate the Header values that are returned –

Use the below code snippet –

describe('GET Service Example', ()=>{

    it("Status Code and Header Validation", ()=>{
           cy.request("https://jsonplaceholder.typicode.com/posts/").as('res')
        .its('status')
        .should('equal', 200);

        cy.get('@res')
           .its('headers')
           .its('content-type')
           .should('include', 'application/json; charset=utf-8');

    });

});

Save it and navigate to the Cypress Test Runner, you will be able to see that tests might have got executed already and the tests are published.

Now, this is a simple GET operation. Lets now try to perform a POST operation with the below code –

describe('GET Service Example', ()=>{

    it.only("Create an Employee",()=>{

        cy.request({
            method:"POST",
            url:"http://dummy.restapiexample.com/api/v1/create",
            body:{
                "name":"test",
                "salary":"123",
                "age":"23"
            }
        })
        .its('status')
        .should('equal', 200)
        .then((response) => {
            expect(response.body).has.property('data').has.property("name","test")
            console.log(response);
          })
    });

});

Code Explanation

We are passing the method as POST and the URL for creating an employee. We are also sending the body with the details.

Once cy.request() executes, we validate the status code returned to be 200. Then we are using assertions to validate whether the response has a name field with a value, test. As simple as that!!!

So, this is how we test the APIs for GET and POST methods. In case if you need more guidance, you can check the Cypress Documentation.

I hope this article will be helpful for you to kick start API tests with Cypress…

References:

https://docs.cypress.io/api/commands/request.html#Syntax

http://dummy.restapiexample.com/

https://jsonplaceholder.typicode.com/posts/

3 thoughts on “Cypress & API Testing in 5 Minutes

Add yours

  1. D:\cypress-api-tests-demo>npm init cypress install –save-dev
    npm ERR! code E404
    npm ERR! 404 Not Found – GET http://registry.npmjs.org/create-cypress – Not foun
    d
    npm ERR! 404
    npm ERR! 404 ‘create-cypress@latest’ is not in the npm registry.
    npm ERR! 404 You should bug the author to publish it (or use the name yourself!)

    npm ERR! 404
    npm ERR! 404 Note that you can also install from a
    npm ERR! 404 tarball, folder, http url, or git url.

    npm ERR! A complete log of this run can be found in:
    npm ERR! C:\Users\Suresh\AppData\Roaming\npm-cache\_logs\2020-02-28T09_34_01
    _140Z-debug.log
    Install for [ ‘create-cypress@latest’ ] failed with code 1n

    What could be issue, when i try above command, getting this error log.

    Like

      1. Yes,

        here I am able to install cypress successfully using: npm install cypress –save-dev command, but not getting why it is throwing error when i use

        npm init cypress install –save-dev

        Like

Leave a comment

Website Powered by WordPress.com.

Up ↑