2

嗨,我正在尝试使用 cypress 自动化分页 api。这个api有两个参数,'pageNo'和'pageSize',pageNo表示在哪个页面,pageSize表示服务器返回的总记录(1页最多15条)。

问题:-我想搜索此 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

 
    
}


        
    });
    
});

提前致谢!!

4

1 回答 1

2

在函数中执行循环。该函数在找到项目时返回,或在下一页重复。

如果它没有找到就进入第 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'))
  })
})
于 2021-08-22T21:44:18.387 回答