Home > Blockchain >  How to get map values by index when inside each loop in JavaScript?
How to get map values by index when inside each loop in JavaScript?

Time:11-04

I try to write tests in a clean way. I iterate through the rows (each of which shows info about attached file) of the table on the page and verify if each attached file has correct size:

   it('attaches many documents', () => {
     const fileSizes = ['17.19 KB', '12.06 KB', '67.75 KB']
     cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath])

   
     cy.get('div.table-body>.table-row').each(($el, index) => {
       expect($el.find('.col-upload-size')).to.contain.text(fileSizes[index])
     })
        
   })

But earlier in the code I have this map defined:

const fileSizesMap = new Map([
    ["excelFileSize", "17.19 KB"],
    ["docxFileSize", "12.06 KB"],
    ["pdfFileSize", "67.75 KB"]
]);

Can I somehow get rid of fileSizes list inside of the test and make use of fileSizesMap instead?

CodePudding user response:

You could try to return an iterable for values and do your assertions:

const fileSizesMap = new Map([
    ["excelFileSize", "17.19 KB"],
    ["docxFileSize", "12.06 KB"],
    ["pdfFileSize", "67.75 KB"]
]);

it('attaches many documents', () => {
    cy.get('input[type="file"]').attachFile([excelFilePath, docxFilePath, pdfFilePath])
    for (const value of fileSizesMap.values()) {
        cy.get('div.table-body>.table-row').then(() => {
            expect($el.find('.col-upload-size')).to.contain.text(value)
        })
    }
})

CodePudding user response:

I understand you want to replace fileSizes with the values from your fileSizesMap:

const fileSizes = Array.from(fileSizesMap.values())
  • Related