我有多个带有 idfeatures-#####和 的div 元素features-#####,其中 # 是一个动态图形。
我如何让 Cypress 找到具有 id 匹配部分的所有元素features-,然后以编程方式单击第一个或第二个?
这是我到目前为止所做的,但我无法弄清楚如何使用正则表达式来检索我所做的所有元素,然后以编程方式处理它们。
describe('builder features component', () => {
it('should allow the user to select a features component', () => {
cy.get(el).should('div.id', /^features-\w+/).first().click();
});
});
Run Code Online (Sandbox Code Playgroud)
Cypress 建议使用data-属性来选择元素。例如,如果您添加data-cy="builder-feature"所有功能,您将不必关心正则表达式,这只会减慢您的测试速度。
cy.get('[data-cy="builder-feature"]').first().click()
Run Code Online (Sandbox Code Playgroud)
请参阅最佳实践。
Rich Churcher是对的,他提到的方法应该是您的首选。但是如果您无法控制应用程序并且无法添加data-cy属性,则可以使用 css 选择器语法来实现此目的。
const featuresSelector = '[id^="features-"]';
Run Code Online (Sandbox Code Playgroud)
这将选择 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
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3716 次 |
| 最近记录: |