我需要打开第一张卡,并验证里面的所有东西都符合‘时尚’标签,然后对接下来的3张卡做同样的操作,然后按下“下一步”按钮,然后对接下来的4张卡做同样的操作。我该怎么做?我尝试了一种常规的方法,点击element.eq(0)
并验证内部的所有内容,然后是cy.go('back')
等等,但这是太多的代码重复。我该怎么做呢?
前4张卡:
第二张4张卡:
它们的CSS选择器都是相同的[class="discover-card"]
。请帮助:)谢谢
发布于 2022-04-05 00:18:50
您可以使用Cypress的.each()
功能来使用相同的CSS选择器迭代元素。
cy.get('.discover-card').each(($card, index) => {
// cy.go('back') can cause the list to become detached, so find element by index of original list.
cy.get('.discover-card').eq(index).click();
// validations after clicking the card
// unsure on this exact function, but was provided in question
cy.go('back').then(() => {
// if this is the fourth item checked, we need to press the next button.
if ((index + 1) % 4 === 0) {
cy.get('.next-btn').click(); // this selector is the next button on the carousel
}
});
});
如果卡片之间的数据是唯一的,我建议创建一个数据对象,您可以使用它来存储数据并在测试中引用它。您可以通过让每个数据对象具有与卡上文本相等的唯一密钥,或者通过将它们存储在数组中来做到这一点。
// unique keys
const data = { fashion: { foo: 'bar' }, beauty: { foo: 'bar2' }, ... };
// array
const data = [{ foo: 'bar' }, { foo: 'bar2' }, ...];
...
// unique keys
cy.wrap($card).should('have.attr', 'foo', data[$card.text()].foo);
// array
cy.wrap($card).should('have.attr', 'foo', data[index].foo);
发布于 2022-04-06 08:40:45
如果您关心代码重复,请将通用代码放在一个函数中。
const expectedData [
{ index: 1, title:'Fashion', ... } // anything you want to check
{ index: 2, title:'Beauty', ... }
]
const checkCard = (cardIndex) => {
const data = expectedData[cardIndex]
cy.get('.discover-card')
.should('contain', data.title)
.click() // open card
// test card internals
}
Cypress._.times(3, (pageNo) => { // loop 3 times between pages
Cypress._.times(4, (cardNo) => { // loop 4 times for cards
const cardIndex = ((pageNo+1) * (cardNo+1)) -1
checkCard(cardIndex)
cy.go.back() // revert to menu
})
cy.get('.next-btn').click()
})
https://stackoverflow.com/questions/71743756
复制相似问题