Suresh Sharma
Suresh Sharma

Reputation: 186

Cypress-get value out of callback function

Hi I am trying to automate pagination api using cypress. This api takes 2 parameters as 'pageNo' and 'pageSize', pageNo means on which page and pageSize means total records returned by server (at max 15 on 1 page).

Problem:- I want to search for a particular fileName that is returned by this api, i don't know on which pageNo it appears, as soon as i found it i have to come out of the both the loops (pageNo and pageSize) Here is my code:-

   describe('Check particular value', function() {

it('Check record', ()=>{

for (let index = 1; index < 7; index++) {    
    cy.request({
        method:"GET",
        url:"https://mydomainName.com/api/v1/searchFile/getFileList",
        qs:{"pageNo":index,"pageSize":15},
        headers:{"authorization": "jwt token "}
    }).then(function(response){
       
        for (let j = 0; j < response.body.data.length; j++) {
         
        if (response.body.data[j].fileName.includes('file_2021_08_20_04_31.txt')) {
                     
            break;            
        }        
           
        }


    });

 // how can i come out of this parent loop

 
    
}


        
    });
    
});

Thanks in Advance!!

Upvotes: 1

Views: 1266

Answers (1)

user16695029
user16695029

Reputation: 4461

Do the loop within a function. The function returns when item is found, or repeats for next page.

If it gets to page 7 without finding, fail the test (or return a message).

const findFile = (expected, pageSize, maxPages, pageNo = 1) => {

  if (pageNo === maxPages) {
    throw `"${expected} was not found`
  }

  return cy.request({
    ...
    qs:{ pageNo ,pageSize },
    ...
  }).then(response => {

    const files = response.body.data
    const foundFiles = files.filter(file => file.fileName === expected)

    if (!foundFiles.length) {  // not on this page, try next
      pageNo = pageNo + 1
      findFile(expected, pageSize, maxPages, pageNo)
    } else {
      return foundFiles  // if you want the matching objects
    }
  })
})

it('finds a file', () => {

  findFile('file123.txt', 15, 7).then(foundFiles => {
    // example further assertion on found files
    foundFiles.forEach(file => expect(file.fileName).to.eq('file123.txt'))
  })
})

Upvotes: 3

Related Questions