How to test APIs with Cypress
Tags: cypress, testing, automtion, e2e
Published: 2021-02-07 20:13:12

## On today's “**Pinches of Cypress**”, learn how to test APIs with **Cypress.io**?

To illustrate, I will use [**ServeRest**](https://serverest.dev/), a project created by [**Paulo Gonçalves**](https://www.linkedin.com/in/paulo-goncalves/) to help with **API testing** studies.

This post will focus only on **GET** requests, ok?

Some of **ServeRest**'s features are the search for **users**, **products**, and **carts**.

Let's start with a **search for users** test.

```js
describe('GET users', () => {
  it('correctly gets users', () => {
    cy.request({
      method: 'GET',
      url: 'http://localhost:3000/usuarios'
    }).then((response) => {
      expect(response.status).to.equal(200);
      expect(response.body.usuarios[0].nome).to.equal('Fulano da Silva')
      expect(response.body.usuarios[0].email).to.equal('fulano@qa.com')
    })
  })
})
```

> **Note:** the endpoints and body responses from **ServeRest** are in Portuguese. Sorry about that!

As you can see in the above code snippet, in addition to checking that the status of the response is successful (`200`), I also perform checks on the structure of the response body to ensure that the **name** (`nome` in PT-BR) and **email** of the first user returned is as expected.

Now, let's look at a **search for products** test, where I want to check more than one product, not just the first.

```js
describe('GET products', () => {
  it('correctly gets products', () => {
    const expectedResult = [
      {
        name: 'Logitech MX Vertical',
        description: 'Mouse',
        price: 470,
        quantity: 382
      },
      {
        name: 'Samsung 60 polegadas',
        description: 'TV',
        price: 5240,
        quantity: 49977
      }
    ]

    cy.request({
      method: 'GET',
      url: 'http://localhost:3000/produtos'
    }).then((response) => {
      expect(response.status).to.equal(200);
      response.body.produtos.forEach((product, index) => {
        expect(product.nome).to.equal(expectedResult[index].name)
        expect(product.descricao).to.equal(expectedResult[index].description)
        expect(product.preco).to.equal(expectedResult[index].price)
        expect(product.quantidade).to.equal(expectedResult[index].quantity)
      })
    })
  })
})
```

In the above example, I define an array with the expected result (which could even come from a **fixture**, but I will talk about this in another post).

The array contains two objects, both with the **name**, **description**, **price**, and **quantity** properties (`nome`, `descricao`, `preco` and `quantidade` in PT-BR).

Finally, I make a `GET` request to the `/products` endpoint, and with the return of the request, I check the success status of the response, in addition to iterating through all the products returned in the response body (using the JavaScript [`forEach`](https://developer.mozilla.org/pt-PT/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) functionality) to verify that the `name`, `description`, `price` and `quantity` are as per the expected result.

As the last example, let's see a test where I **search for carts**, passing as a specific **total quantity** as **queryString**.

```js
describe('GET carts', () => {
  it('correctly gets carts by total quantity', () => {
    cy.request({
      method: 'GET',
      url: 'http://localhost:3000/carrinhos?quantidadeTotal=3'
    }).then((response) => {
      expect(response.status).to.equal(200);
      expect(response.body.carrinhos.length).to.equal(1)
    })
  })
})
```

In the above test, I verify that only one **cart** was returned in the cart's array from the body of the response (using the [`length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length) property), in addition to the success status, of course. 😉

Running the three tests above locally, they all passed, and in just 146ms. 🚀

___

I keep collecting feedback and creating a backlog for the next posts. Leave a comment with what you would like me to address in future content.

___

This post was originally published in Portuguese on the [**Talking About Testing**](https://talkingabouttesting.com/2021/02/07/como-verificar-a-estrutura-do-body-de-um-esquema-json-com-cypress/) blog.
___

Would you like to learn about **test automation with Cypress**? Get to know my online courses on [**Udemy**](https://udemy.com/user/walmyr).

___

> **Spoiler**: in 2021, there will be an **API testing with Cypress course** at the [**Talking About Testing**](https://udemy.com/user/walmyr) school. Stay tuned!