【问题标题】:cypress not executing "then" portion赛普拉斯没有执行“then”部分
【发布时间】:2021-06-01 15:19:13
【问题描述】:

我正在尝试编写自定义 cypress 命令,但我的 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++
    }
  })
})

【问题讨论】:

  • 请不要将代码作为图像放在这里 :) 我们很难自己尝试。
  • 感谢您的反馈,但我在远程计算机上,无法从中复制。对不起
  • .then(() 可以是这个吗?但它必须是这个?.then(),我不确定我之前从未真正使用过这个命令或这个库,但是那个似乎在这里最明显
  • 我得说,你真的需要正确地格式化你的代码,因为后面的所有花括号和括号都很难理解

标签: testing automated-tests cypress e2e-testing


【解决方案1】:

这里有一些事情我们应该逐步完成。

在您的each() 块中,link.href 将返回一个未定义的值,因此当您访问您的then 方法时,您的数组中没有可访问的链接。而不是links.push(link.href),尝试links.push(links.attr('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'))
      })
    })
});

【讨论】:

  • 这不起作用 cypress 返回 links.forEach 不是函数
  • @Alien0w0 答案已更新。试试links.each 而不是links.forEach
  • 要么用.each( 替换.then(,要么用[...links].forEach(link => ... 解构jQuey links 对象。
【解决方案2】:

补充克里的回答,

.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)
      })

    })
});

或者如果您想使用赛普拉斯迭代器 .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))
  })

【讨论】:

  • 这是我答案的一个很棒的附录,应该标记为答案。感谢您的详细和清晰!
猜你喜欢
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
相关资源
最近更新 更多