简体   繁体   中英

Cypress iterate through elements in an array

I am struggling iterating through elements in an array using cypress/typescript. I am logging everything great and able to see each index and what it shows but I am still returning the entire array vs the actual index and two days later I cannot figure out how to grab the actual index [0], [1], [2], etc. I have a tried a lot of things but this is what I have as my latest try. Thanks for any help ending my suffering!

    sportPage.getFirstCard().within(() => {
      sportPage.getSecondSection().within(() => {
        sportPage
          .getMyCoolType()
          .should('exist')
          .each(($item, $index) => {
            cy.wrap($item)
              .invoke('text')
              .then((text) => {
                if ($index !== 0) values.push(text);
                cy.log($index.toString());
                cy.log(text);
              });
          })
          .then(() => expect(values.toString()).to.equal('Yoga');
      });
    });
  });
});

To test the individual texts in the array of elements returned by .getMyCoolType() ,

sportPage.getFirstCard().within(() => {
  sportPage.getSecondSection().within(() => {
    sportPage
      .getMyCoolType()
      .should('exist')
      .each(($item, $index) => {
        cy.wrap($item)
          .invoke('text')
          .then((text) => {
            cy.log($index.toString());
            cy.log(text);
            if ($index !== 0) {
              expect(text.trim()).to.equal('Yoga');
            }
          });
      })
  });
});

Or to test all items after the loop

sportPage.getFirstCard().within(() => {
  sportPage.getSecondSection().within(() => {
    sportPage
      .getMyCoolType()
      .should('exist')
      .each(($item, $index) => {
        cy.wrap($item)
          .invoke('text')
          .then((text) => {
            if ($index !== 0) values.push(text);
            cy.log($index.toString());
            cy.log(text);
          });
      })
      .then(() => expect(values.every(item => item === 'Yoga')).to.equal(true) );
  });
});

You might also get away with this

sportPage.getFirstCard().within(() => {
  sportPage.getSecondSection().within(() => {
    sportPage
      .getMyCoolType()
      .should('exist')
      .then(($items) => {
        const texts = [...$items].map(item => item.text()); // map elements into texts
        return texts.slice(1);                              // ignoring the first one
      })
      .then((items) => expect(items.every(item => item === 'Yoga')).to.equal(true) );
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM