Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search through JSON response with Cypress assertions

Considering the below API response I would like to assert the exact location of a certain value in a JSON structure. In my case the name of pikachu within forms:

"abilities": [
{
"ability": {
"name": "lightning-rod",
"url": "https://pokeapi.co/api/v2/ability/31/"
},
"is_hidden": true,
"slot": 3
},
{
"ability": {
"name": "static",
"url": "https://pokeapi.co/api/v2/ability/9/"
},
"is_hidden": false,
"slot": 1
}
],
"base_experience": 112,
"forms": [
{
"name": "pikachu",
"url": "https://pokeapi.co/api/v2/pokemon-form/25/"
}]

I would like to extend below code snippet to not scan the entire body as a whole as there are a lot of name's in the response, but rather go via forms to exactly pinpoint it:

describe('API Testing with Cypress', () => {

  var baseURL = "https://pokeapi.co/api/v2/pokemon"

  beforeEach(() => {
      cy.request(baseURL+"/25").as('pikachu');
  });


it('Validate the pokemon\'s name', () => {
      cy.get('@pikachu')
          .its('body')
          .should('include', { name: 'pikachu' })
          .should('not.include', { name: 'johndoe' });
  });

Many thanks in advance!

like image 346
FransPeterson Avatar asked Sep 06 '25 23:09

FransPeterson


2 Answers

Getting to 'forms' is just a matter of chaining another its(), but the 'include' selector seems to require an exact match on the object in the array.

So this works

it("Validate the pokemon's name", () => {
  cy.get("@pikachu") 
    .its("body")
    .its('forms')
    .should('include', { 
      name: 'pikachu', 
      url: 'https://pokeapi.co/api/v2/pokemon-form/25/' 
    })
})

or if you just have the name,

it("Validate the pokemon's name", () => {
  cy.get("@pikachu") 
    .its("body")
    .its('forms')
    .should(items => {
      expect(items.map(i => i.name)).to.include('pikachu')
    })
})

and you can assert the negative,

  .should(items => {
    expect(items.map(i => i.name)).to.not.include('johndoe')
  })
like image 151
Richard Matsen Avatar answered Sep 09 '25 16:09

Richard Matsen


Can you try the below code and see if it helps with your expectation. From the response you could get the name as below;

describe('API Testing with Cypress', () => {
    var baseURL = "https://pokeapi.co/api/v2/pokemon"
    beforeEach(() => {
        cy.request(baseURL+"/25").as('pikachu');
    });

  it('Validate the pokemon\'s name', () => {
        cy.get('@pikachu').then((response)=>{
            const ability_name = response.body.name;
            expect(ability_name).to.eq("pikachu");
        })    
    });
})

enter image description here

like image 42
soccerway Avatar answered Sep 09 '25 16:09

soccerway