我正在嘗試創建一個自動化測驗來簡單地驗證內容是否存在/是否顯示有嵌入在文本中的超鏈接。請在附件中找到我的螢屏截圖以獲取更多資訊,我只是想驗證紅框中的所有內容。我還突出顯示了 google 開發工具中的代碼。

uj5u.com熱心網友回復:
您可以嘗試在“li”元素中找到一個“a”元素并檢查它的 href 屬性和內部文本。
cy.get(selector)
.find("a")
.should("have.attr", "href", "/path")
.should("have.text", "Alcohol Anonymous");
uj5u.com熱心網友回復:
查看 cypress 團隊的這篇博文。他們解釋了您可以使用 cypress 測驗鏈接的所有不同方法
https://www.cypress.io/blog/2020/12/10/testing-the-anchor-links/
向下滾動到Checking every link我認為你想要的部分
uj5u.com熱心網友回復:
如果要檢查確切的文本,可以創建這樣的陣列。
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])
})
或者,如果您只是檢查內容和超鏈接是否都存在,您可以這樣做:
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')
})
uj5u.com熱心網友回復:
@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])
})
})
uj5u.com熱心網友回復:
這很容易,并且以下兩行代碼足以驗證:
代碼片段
cy.contains("a","Alcohol Anonymous").invoke('attr','href')
.should('include','/ attr value')
cy.contains("li", "text").should('be.visible)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/441637.html
標籤:javascript 测试 自动化 自动化测试 柏
