简体   繁体   English

Cypress-从回调中获取值 function

[英]Cypress-get value out of callback function

Hi I am trying to automate pagination api using cypress.您好我正在尝试使用柏树自动分页 api。 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).这个 api 需要 2 个参数作为 'pageNo' 和 'pageSize',pageNo 表示在哪个页面上,pageSize 表示服务器返回的总记录(一页最多 15 条)。

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:-问题:- 我想搜索此 api 返回的特定文件名,我不知道它出现在哪个 pageNo 上,一找到它我就必须退出两个循环(pageNo 和 pageSize)这是我的代码:-

   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!!提前致谢!!

Do the loop within a function. The function returns when item is found, or repeats for next page.在 function 中执行循环。function 在找到项目时返回,或重复下一页。

If it gets to page 7 without finding, fail the test (or return a message).如果它到达第 7 页仍未找到,则测试失败(或返回消息)。

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'))
  })
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM