簡體   English   中英

賽普拉斯 - 找不到元素

[英]Cypress - Element not found

找不到元素時如何克服這種情況。 我正在自動化一個表格,我故意在其中提供重復的名稱,因此將根據我所寫的內容顯示錯誤消息“限制名稱已存在”

   add.limitName().type('Movie Limits') // Giving duplicate name "Movie Limits"

   cy.get('.has-error > .col-sm-6 > [data-bv-validator="remote"]').then((wizard) => {
       if(wizard.text().includes('Limit Name already exist.'))  // Duplicate Limit Name Check
       {
           add.limitName().clear()
           add.limitName().type('Movie TR Limits')   // Giving another Name
       }
     })

如果它是一個重復值,這將完全正常工作,但如果它不是重復值,則不會找到該元素並拋出錯誤並且測試失敗。 如果它不重復它繼續並且如果上面的代碼生效,我怎么能以這種方式編寫?

當錯誤丟失時,測試失敗似乎是完全合法的,但要回答你的問題

拆分最后一個選擇器並使用 jQuery(不會導致失敗)檢查它,而不是將其包含在 Cypress cy.get()中。

cy.get('.has-error > .col-sm-6')
  .then($col => {
    // test the last element with jquery by checking it's length
    if ($col.find('[data-bv-validator="remote"]').length === 0) {
      ...

假設當沒有錯誤時,元素.has-error本身將不存在於 dom 中。 所以你可以這樣做:

cy.get('body').then(($body) => {
  if ($body.find('.has-error').length > 0) {
    //Element found
    cy.get('.has-error').should('include.text', 'Limit Name already exist.')
    add.limitName().clear()
    add.limitName().type('Movie TR Limits')
  } else {
    //Error element not found.Write further code.
  }
})

如果 class 可能存在也可能不存在,則您應該使用.has-error以外的其他選擇器。

cy.get('my-selector').then($el => {
  if ($el.hasClass('has-error')) {

    cy.get('.has-error > .col-sm-6 > [data-bv-validator="remote"]')
      .then(wizard => {
        ...
      })

  } else {
    ...
  }
})

.type()命令后可以查看錯誤class

add.limitName().type('Movie Limits') 
  .then($el => {

    if ($el.hasClass('has-error')) {

      cy.get('.has-error > .col-sm-6 > [data-bv-validator="remote"]')
        .then((wizard) => { ...
        });
    }
  });

假設帶有.has-class的元素不是您輸入的<input> ,請使用.parent()檢查 class 是否存在。

add.limitName().type('Movie Limits') 

cy.get('[data-bv-validator="remote"]')
  .parent()                            // up to ".col-sm-6"
  .parent()                            // up to element which (maybe) has ".has-error"
  .then($el => 

    if ($el.hasClass('has-error')) {

      cy.get('.has-error > .col-sm-6 > [data-bv-validator="remote"]')
        .then((wizard) => { ...
        });
    }
  })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM