首页 > 解决方案 > 赛普拉斯一开始就停止

问题描述

当我针对该 HTML 代码运行测试时

<body>
  <div tester='notmatching'>
    foo
  </div>
  <div tester='matching'>
    bar
  </div>
</body>

</html>

赛普拉斯并没有超越第一个“div”。

这是我的测试:

context('Home', () => {
  beforeEach(() => {
    cy.visit('http://example.org')
  })
  it('Find a div', () => {
    cy.get('div').should('have.attr', 'tester', 'matching')
  })
})

我收到以下错误:

CypressError: Timed out retrying: expected '[ <div>, 1 more... ]' to have attribute 'tester' with the value 'matching', but the value was 'notmatching'

所以当我把这条线:

cy.get('div').should('have.attr', 'tester', 'notmatching')

有用。

我究竟做错了什么 ?

标签: javascripte2e-testingcypress

解决方案


我认为您必须使用 eq 定位第二个匹配元素:

cy.get('div').eq(1).should('have.attr', 'tester', 'matching')

https://docs.cypress.io/api/commands/eq.html#Syntax

编辑:

如果你想遍历它们并检查每一个,你可以这样做:

cy
  .get('div')
  .each(($el, index, $list) => {
    if ($el.attr('tester') === 'matching') {
      // do something here

编辑2:

如果您只想将 div 与该属性匹配 - 您可以这样做:

cy.get("div[tester='matching']").should(...

推荐阅读