Beginner API Testing with Cypress

Denise Andron
3 min readAug 31, 2023

--

In this short post, I want to share with you a simple way you can test an API call with Cypress.

In this example I will be using a demo site ‘demoblaze’, I already set up Cypress commands to navigate to the site in ‘commands.js’, here:

Created the first test and added beforeEach where we call the above:

In this API test, first I want to add items to the cart, navigate to the cart and intercept the call, assert that the status code is 200.

But first, we need to do all the steps to add the items to test, here:

To intercept the API call, we need to see the URL in the browser ‘Network’ and get the request method:

Then we use cy.intercept() , we need to use it before all of our tests, here:

We use the request method ‘POST’ and the URL from the network area I showed above, then we give the call a name ‘itemsCart’. We wait for the call and then we get it with cy.wait() and cy.get()

After we save and use npx cypress open, after the test is ran, we can see our API route:

Inspect the browser and go to the console after clicking on the call:

Here we can see the response body with the item we added to the cart

Assert that the status code was 200 ok

Run the test and check the assert:

The assertion is correct, you can also use the body of the request to take on the information, unfortunately I do not have useful information on this demoblaze website, so my body only contains the id, but for other API you can use something like this:

expect(xhr.response.body.name.description).to.equal('Description in body')

Hope this helps!

--

--