DEV Community

Cover image for Using Cypress for API tests
Rodrigo Santos
Rodrigo Santos

Posted on

Using Cypress for API tests

Hey, today I'm here to show you how we can use Cypress for testing APIs but, before this, I have one disclaimer for you.

I assume you know the basics about Javascript, Cypress, and your setup, so I will just skip the setup of cypress and introductions about the technology.

In this post, I using the JSON Placeholder API for tests, but you can use any API of your preference. We are going to use cy.request for sending requests for API, so in our requests, we will use this structure:

cy.request(method, url, body)

So let's start the fun

First, we need to send our request to have something for the test, right? We will the /posts endpoint in this case, but you can use others, no problem. I separated the test case into two parts, first I show the request body, and the second part, our tests.

    cy.request({
        method: 'POST',
        url: 'posts',
        body: {
            title: 'Something Interested',
            body: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.',
            userId: 1
        }
     })
Enter fullscreen mode Exit fullscreen mode

In request, we are creating a post with the title Something Interested in user of ID is 1. According to the documentation of API, the response should have four params, so now, we go check this and explore the ways Cypress provides for API tests.

.then((response) => {
            expect(response.status).to.eq(201)
            expect(response.body).to.have.property('id')
            expect(response.body).to.have.property('title', 'Something Interested')
            expect(response.body).to.have.property('body', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.')
            expect(response.body).to.have.property('userId')
        })
Enter fullscreen mode Exit fullscreen mode
  • expect(response.status).to.eq(201): How the request is for creating a post, we need to receive a 201 status code, what is Created.
  • expect(response.body).to.have.property('title', 'Something Interested'): Here we are checked if a title post is correct.
  • expect(response.body).to.have.property('body', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.'): In this test, we are checked if a body post is correct.
  • expect(response.body).to.have.property('userId'): So in this case, we are verifying if in the response body the user ID exists.

In Cypress exists some other methods for test API and you can find them in documentation, this post was an example of what Cypress can do. The full project are in my github, if you want to see closer.
So thank for your time and I hope it helps.

Discussion (0)