我有多个带有id features-#####
和features-#####
的div元素,其中#是一个动态图形。
如何让Cypress找到id features-
的匹配部分的所有元素,然后以编程的方式单击第一个或第二个元素?
这是我到目前为止所做的,但是我无法找到使用regex检索所有元素的hwo,然后以编程方式处理它们。
describe('builder features component', () => {
it('should allow the user to select a features component', () => {
cy.get(el).should('div.id', /^features-\w+/).first().click();
});
});
发布于 2020-04-20 22:23:39
Cypress建议使用data-
属性来选择元素。例如,如果将data-cy="builder-feature"
添加到所有功能中,您就不必关心那些只会减慢测试速度的正则表达式。
cy.get('[data-cy="builder-feature"]').first().click()
见最佳实践。
发布于 2020-04-21 01:49:59
富丘吉尔是对的,他提到的方法应该是你的首选。但是,如果您无法控制应用程序,并且无法添加data-cy
属性,则可以使用css选择器语法来实现这一点。
const featuresSelector = '[id^="features-"]';
这将选择以.开头的任何id元素。在如何选择ID以特定字符串开始和结束的所有元素?看到一个很好的解释
然后您可以这样使用这个选择器:
cy.get(featuresSelector).first().click(); // click the 1st element in the collection
cy.get(featuresSelector).eq(1).click(); // click the second element (index starts at 0)
cy.get(featuresSelector).eq(-1).click(); // click the last element
cy.get(featuresSelector).each((element, index, collection) => {
// or event loop through the entire collection
})
发布于 2020-04-20 22:18:04
使用contains()函数。该函数可以接收regex作为参数。
cy.contains(/^features-\w+/).click();
https://stackoverflow.com/questions/61332700
复制相似问题