我正试图编写一个自定义的Cypry命令,但我的then部分中的代码没有执行。任何帮助都将不胜感激,谢谢我的命令看起来像这样:
Cypress.Commands.add("ex", () => {
const links=[]
cy.get("*[class='link post']").each((link)=>{
links.push(link.href)
}).then(() => {
var i=0;
while (links[i]) {
cy.visit(link)
i++
}
})
})
这里有一些事情我们应该逐步了解。
在each()
块中,link.href
将返回一个未定义的值,因此当您使用then
方法时,数组中没有可访问的链接。尝试links.push(links.attr('href')
而不是links.push(link.href)
来获取href
属性的值。
在then
方法中,while
循环并不是在数组中循环的最有效方式(它很可能会因未定义的值而出错(。您应该使用.forEach()
,如下所示:
links.forEach((link)=>{
cy.visit(link)
)
如果您不需要持久化links
数组,那么您的整个命令可以大大简化:
Cypress.Commands.add("ex", () => {
cy.get("*[class='link post']")
.then((links) => {
links.each((link)=>{
cy.visit(link.attr('href'))
})
})
});
要添加到Kerry的答案中,
给.then()
回调的参数是一个jQuery对象,包含cy.get(...)
找到的一个或多个元素
要迭代元素,您需要使用排列运算符来分解jQuery对象的结构
Cypress.Commands.add("visitLinks", () => {
cy.get("*[class='link post']")
.then($links => { // $links is a jQuery wrapper
[...$links].forEach(link => { // link is a raw element
const url = link.getAttribute('href') // apply DOM method
cy.visit(url)
})
})
});
或者,如果您想使用Cypress迭代器.each()
而不是.then()
,
Cypress.Commands.add("visitLinks", () => {
cy.get("*[class='link post']")
.each($link => { // jQuery wrapped element
const href = $link.attr('href') // apply jQuery method
cy.visit(href)
})
});
但是
它要坏了。
cy.visit()
导航页面,这会更改页面中的DOM,因此在.each()
的第二次迭代中,Cypress看到情况发生了变化并崩溃(可能是"分离元素"错误(。
您应该将查询(获取链接(与操作(访问链接(分开。
Cypress.Commands.add("getLinks", () => {
const found = [];
cy.get("*[class='link post']")
.each($link => { // jQuery wrapped element
const href = $link.attr('href') // apply jQuery method
found.push(href)
})
.then(() => found) // wait until iteration finishes
// then return the array of links
});
像这样使用
cy.getLinks()
.then(links => {
links.forEach(link => cy.visit(link))
})