Kin*_*ght 2 javascript cypress
尝试在 cypress 中执行 if 语句来查找页面上的所有标签,如果它们有 href 那么它不应该为空。
这是我到目前为止所得到的:
cy.get("a").each($el => {
cy.wrap($el)
.should("have.attr", "href")
.and("include", "/");
});
Run Code Online (Sandbox Code Playgroud)
然而,即使它没有 href,它也会检查所有内容。
小智 5
贾斯汀·史密斯答案的更新版本,删除了不必要的回调。
只是为了说明赛普拉斯链接命令的可读性。
消除噪音,只需使用链接
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
Run Code Online (Sandbox Code Playgroud)
请注意,此模式与 Cypress 7 无关,它已适用于许多以前的版本。
检查所有href
该问题实际上要求一种检查页面上所有标签的方法。
例如,
<a></a> -- should ignore
<a href="/foo"></a> -- should pass
<a href="/"></a> -- should pass
<a href=""></a> -- should fail
Run Code Online (Sandbox Code Playgroud)
一种方法是通过在元素选择器内cy.get()移动谓词来更具选择性。.should("have.attr", "href")
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
})
Run Code Online (Sandbox Code Playgroud)
柏木原木
| 1 | 得到 | 一个[参考] | 3 | 经过 |
| 2 | 断言 | 预计/包括/ | 经过 | |
| 3 | 断言 | 预期 /foo 包含 / | 经过 | |
| 4 | 断言 | 预期 '' 包括 / | 失败 |