簡體   English   中英

檢查元素是否具有 href 如果它不應該為空 Cypress.io

[英]Check if element has href if it does it shouldn't be empty Cypress.io

嘗試在 cypress 中執行 if 語句,查找頁面上的所有標簽,如果它們有 href,那么它不應該為空。

這是我到目前為止所得到的:

cy.get("a").each($el => {
    cy.wrap($el)
     .should("have.attr", "href")
     .and("include", "/");
});

但是,即使它沒有href,這也會檢查所有內容。

賈斯汀史密斯答案的更新版本,刪除了不必要的回調。

只是為了說明 Cypress 鏈式命令的可讀性。

去除噪音,只需使用鏈接

cy.get('Selector for the anchor tag')      // sets <a> as the subject
  .should('have.attr', 'href')             // changes subject to href attribute
  .should('not.be.empty')                  // now test the href
  .and('contain', 'foo');                  // also test another criteria here

請注意,此模式與 Cypress 7 無關,它已可用於許多以前的版本。


檢查所有的href

該問題實際上要求一種檢查頁面上所有標簽的方法

例如,

<a></a>                      -- should ignore
<a href="/foo"></a>          -- should pass
<a href="/"></a>             -- should pass
<a href=""></a>              -- should fail

一種方法是通過在元素選擇器中移動.should("have.attr", "href")謂詞來在cy.get()更具選擇性。

cy.get("a[href]")                           // get all <a> that have an href
  .each($el => {                            // test individually
    cy.wrap($el.attr('href'), {log:false})  // here we need to cy.wrap
      .should("include", "/")               // because subject needs to change
  })                                      

柏樹日志

1 得到 [href] 3 經過
2 斷言 預期 / 包括 / 經過
3 斷言 預期 /foo 包括 / 經過
4 斷言 預期 '' 包括 / 失敗

這是 T Gurung 答案的更新版本。

cy.get('Selector for the anchor tag')
  .should("have.attr", "href")
  .should("not.be.empty")
  .and("contain", "foo");

你可以說應該沒有帶有空白 href 的 A 元素

cy.get('a').get('[href=""]').should('length',0);

或者

cy.get('a').get('[href=""]').should('not.exist');

如果需要,您也可以說不應該有沒有 href 標簽的 A 元素,我不確定這是否是必需的

cy.get('a:not([href])').should('not.exist');

你可以這樣做:

cy.get('Selector for the anchor tag')
     .should('have.attr', 'href')
     .then((href) => {
        expect(href).should('not.be.empty')  //To assert, not to be empty
        expect(href).to.contain('foo')   //If you want to assert for something specific to be there
     })

我已閱讀 Zauni 的評論並嘗試一下。

賽普拉斯 ^10.3.1

cy.get({selector}).wrap('href').should('not.be.empty');

完美工作。

暫無
暫無

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

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