简体   繁体   English

Cypress 遍历数组中的元素

[英]Cypress iterate through elements in an array

I am struggling iterating through elements in an array using cypress/typescript.我正在努力使用 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.我正在记录一切,并且能够看到每个索引及其显示的内容,但我仍然返回整个数组与实际索引,两天后我无法弄清楚如何获取实际索引 [0]、[1]、[ 2] 等。我尝试了很多东西,但这是我最近的尝试。 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() ,要测试.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) );
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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