Search code examples
arraysloopscypress

Cypress test throws an error message when using an array


In a cypress test case I use this line of code and cypress throws an error message that I do not understand. No idea what to do. Any idea? Any solution possible?

Code:

const months = [
        'JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'
      ];
  
      // Create an object to store the values dynamically
      const values = {};
  
      // Use a loop to iterate over each month
      months.forEach((month, index) => {
        cy.get('.tabele1 > tbody > tr.table_row3 > td:nth-child(1)').each(($e1, rowIndex, $list) => {
          var titletext = $e1.text();
          if (titletext.includes('Some Headline Text')) {
            cy.get(`.table1 > tbody > tr.table_row3 > td:nth-child(${index + 2})`).eq(rowIndex).then(function (amount) {
              // Dynamically store values in the object
              values[`valueMA_${month}1`] = amount.text().trim();
            });
          }
        });
      });

      // Example assertions in a loop
    months.forEach((month, index) => {
        expect (values[`valueMA_${month}1`]).to.equal('400');
    });

Cypress error message:

AssertionError
expected undefined to equal '400'

The error refers to this line of code:

expect (values[`valueMA_${month}1`]).to.equal('400');

What is wrong with the code? I do not see it ...

Thank you very much!


Solution

  • Move ,

    expect (values[valueMA_${month}1]).to.equal('400');

    Into your previous forEach() function, as below

    cy.get('.table1 > tbody > tr.table_row3 > td:nth-child(${index + 2})).eq(rowIndex).then(function (amount) { expect(amount.text().trim()).to.equal('400'); });

    Hope this helps