How to pass files name in array and then iterating for the file upload functionality in cypress

Viewed 510

I am trying to create a for loop where I will pass all the files in the list using beforeEach and then I want to iterate the list in order to upload file via api call.

I have placed all my files under cypress/fixture/files folder.

I want to add the file that is under the fixture/files folder into the array like below:

beforeEach(() => {
  cy.fixture('files/').as('files')
});

And then I want to iterate the files array to upload the files via api call.

I used below code to iterate:

cy.wrap(files).each((index) => {
  const fileName = files[index];

When I try to use above code I get below error. I am not sure if I am using the right approach.

enter image description here

1 Answers

I'm not sure if this solves the issue, but the way you use the alias is not correct. You need to cy.wait('@files') to get the value of the alias. cy.get('@files') is also correct syntax but will not work here since cy.fixture() reads from the disk (so you must wait for it to complete).

Since you use the files straight after loading them, get rid of the alias and use a .then() to wait

/*
  Fixture file contains:
  { 
    "uploadFilePng": "files/cypressFileUpload.png", 
    "uploadFileDmg": "files/cypressFileUpload.dmg", 
    ...
  }
*/

cy.fixture('files/cypressFileUpload').then(files => {
  const fileNames = Object.values(files);
  cy.wrap(fileNames).each(fileName => {
    console.log(fileName); // should see "files/cypressFileUpload.png", "files/cypressFileUpload.dmg"
    ...
Related