在Cypress测试中,我试图单击嵌套在div内的特定按钮,基于它的文本。
下面是我要测试的HTML代码:<div class="mat-menu-content">
<button>First button</button>
<button>Second button</button>
</div>
我想点击带有Second button
文本的按钮。
我不能只使用cy.contains('Second button')
,因为Second Button
文本出现在页面的多个地方。
这是我想用Cypress写的东西:
- 点击
mat-menu-content
div内包含Second button
文本的按钮
谁能告诉我这是怎么做的?
您应该首先通过类名获取元素,然后搜索内容,最后调用click()方法。试试这样做:
cy.get('.mat-menu-content').contains('Second button').click()
更多信息,请看这里的官方文档
.contains()
是非常强大的,允许使用一个选择器与文本配对,cy.contains('selector', 'Your text')
。
对于您的场景,您将希望使用与文本配对的button
选择器来获取包含Second button
的按钮。
cy.contains('button', 'Second button')
// or if there are multiple buttons with 'Second button' text on the page
cy.get('.mat-menu-content')
.contains('button', 'Second button')
.contains()
也允许regex匹配,我更喜欢在不区分大小写的情况下查找。
cy.contains('button', /second button/i)
又一个变化,在button
选择器之前添加.mat-menu-content
cy.contains('.mat-menu-content button', 'Second button') // tighter criteria
如果你的网页上有多个mat-menu-content
,你可以使用eq
访问一个特定的,然后使用within()
在div.mat-menu-content
范围内查询
cy.get('mat-menu-content')
.eq(0)
.within(() => {
//eq(0) points to the first occurance in the DOM
cy.contains('button', 'Second button').click()
})
如果页面上有多个菜单,则项目按钮仅在菜单打开时显示,并且一次只打开一个菜单。
你可以在打开按钮的菜单后选择文字为Second button
的按钮。
cy.contains('button', 'Contacts Menu').click() // open the menu
cy.contains('button', 'Second button').click() // select 2nd item
当你想做'点击mat-menu-contentdiv中包含第二个按钮文本的按钮'时,我建议
cy.get('div.mat-menu-content button').contains('Second button').click()
下面是一个get
命令,正好满足您的需求:
cy.get('div.mat-menu-content button:contains("Second button")'