Search code examples
javascriptloopsfor-loopautomationcypress

How can I download and name the downloaded file using loop in cypress?


describe('download',function()
{
it('fils',function()
{
  
cy.visit('url')
cy.get('.ds_class_data_sheet').click()
cy.wait(3000)
const numberoftest=68;
for (let i = 1; i <= numberoftest; i ++) {    
  
cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink').eq(i).then(function(e1)
{
  const url=e1.prop('href')
  
  cy.downloadFile(url,'cypress/downloads/Datasheet','file1.pdf')
  
}

)
}

  

}



)
})

I tried by writing the code like this. There happen the downloads but my question is how do I name the downloaded file using the loop.


Solution

  • To change the name inside the loop, use a string template.

    for (let i = 1; i <= numberoftest; i ++) {    
      cy.get('.dsDocumentData > .dsTitle > .dsDocumentLink').eq(i)
        .then(function(e1) {
          const url = e1.prop('href')
    
          // name whatever format desired, maybe last part of url
          const id = url.split('/')[3]
          const name = `file_${id}`      
    
          cy.downloadFile(url,'cypress/downloads/Datasheet', name)
        })
    }