簡體   English   中英

賽普拉斯如何驗證帶有超鏈接的內容?

[英]How can Cypress verify content with hyperlinks?

我正在嘗試創建一個自動化測試,它只是驗證內容是否存在/顯示是否帶有文本中嵌入的超鏈接。 請查看附件中的截圖以獲取更多信息,我只是想驗證紅色框中的所有內容。 我還突出顯示了谷歌開發工具中的代碼。

在此處輸入圖像描述

您可以嘗試在“li”元素中找到一個“a”元素並檢查它的 href 屬性和內部文本。

cy.get(selector)
    .find("a")
    .should("have.attr", "href", "/path")
    .should("have.text", "Alcohol Anonymous");

查看 cypress 團隊的這篇博文。 他們解釋了使用 cypress 測試鏈接的所有不同方法

https://www.cypress.io/blog/2020/12/10/testing-the-anchor-links/

向下滾動到Checking every link部分,這是我認為你想要的

這很容易,下面兩行代碼就足以驗證:

代碼片段

   cy.contains("a","Alcohol Anonymous").invoke('attr','href')
     .should('include','/ attr value')
   cy.contains("li", "text").should('be.visible)

如果你想檢查確切的文本,你可以創建一個這樣的數組。

const texts = [
  'Alcohol Anonymous',
  'Cance Research',
  'Cancer Trust',
  'Drinkware',
] //Add the remaining texts

cy.get('a').each(($ele, index) => {
  cy.wrap($ele).should('have.text', texts[index])
})

或者,如果您只想檢查所有鏈接是否都有一些文本,您可以這樣做:

cy.get('a').each(($ele, index) => {
  cy.wrap($ele).invoke('text').should('not.be.empty')
})

現在,如果你想同時檢查內容和超鏈接,你可以這樣做:

const texts = [
  'Alcohol Anonymous',
  'Cance Research',
  'Cancer Trust',
  'Drinkware',
] //Add the remaining texts
const links = [
  'https://example1.com',
  'https://example2.com',
  'https://example3.com',
  'https://example4.com',
] //Add the remaining links

cy.get('a').each(($ele, index) => {
  cy.wrap($ele)
    .should('have.text', texts[index])
    .and('have.attr', 'href', links[index])
})

或者,如果您只是 ant 檢查內容和超鏈接是否都存在,您可以執行以下操作:

cy.get('a').each(($ele, index) => {
  cy.wrap($ele).invoke('text').should('not.be.empty')
  cy.wrap($ele).invoke('attr', 'href').should('not.be.empty')
})

@GustavoCesário 是正確的,您必須定位包含鏈接的頁面部分。

如果您嘗試cy.get('a') ,您將獲取徽標、導航菜單等,但這不是您要測試的內容。

此外,對於全文,您需要<li>而不是<a>

const expectedParagraphs = [
  'Alcohol Anonymous is a free support group that offers help for anyone choosing to stop drinking.',
  'Cancer Research provides information on how alcohol affects your risk of the disease.',
  'Carers Trust gives help to people who are affected by someone else’s drinking.',
  ...
]

beforeEach(() => {
  cy.visit('https://www.drinkiq.com/en-gb/get-help/');
})

it('checks the list texts', () => {

  cy.get('main')
    .find('li')
    .each(($li, i) => {
      const paragraph = $li.text()
      expect(paragraph).to.eq(expectedParagraphs[i])
    })
})

暫無
暫無

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

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