比较页面操作前后功能调用的结果

发布于 2025-02-09 08:50:04 字数 465 浏览 0 评论 0原文

我有一个复杂的选择,我将其投入了一个功能,以保持测试清洁。我想在某些页面操作之前和之后调用该功能并比较结果。

这是我的代码,问题是,即使在功能中成功提取了值,我也不会收回结果。

const getVals = () => {
  // simplified
  cy.get('[id="22"] span')
    .then($els => {
      const vals = [...$els].map(el => el.innerText)
      return vals
    })
}

const vals1 = getVals()

// perform action on the page

const vals2 = getVals()

// compare
expect(vals1).to.deep.eq(vals2)

I have a complicated selection that I've put into a function to keep the test clean. I want to call the function before and after some page actions and compare the results.

This is my code, problem is I'm not getting the result back even though the value is extracted successfully inside the function.

const getVals = () => {
  // simplified
  cy.get('[id="22"] span')
    .then($els => {
      const vals = [...$els].map(el => el.innerText)
      return vals
    })
}

const vals1 = getVals()

// perform action on the page

const vals2 = getVals()

// compare
expect(vals1).to.deep.eq(vals2)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

各自安好 2025-02-16 08:50:04

该函数在内有一个返回。

由于命令是异步的,我建议更改为自定义命令并添加别名以保留中间操作期间的结果

Cypress.Commands.add('getVals', () => {
  cy.get('[id="22"] span')
    .then($els => {
      const vals = [...$els].map(el => el.innerText)
      return vals                    // vals is Cypress "subject" 
    })
}

cy.getVals().as('vals1')

// perform action on the page

cy.getVals().then(vals2 => {         // use then to obtain vals
  cy.get('@vals1').then(vals1 => {   // retrieve first from alias
    // compare
    expect(vals1).to.deep.eq(vals2)
  })
})

The function has a return inside .then() but it's not returning the result from the main body of the function.

Since the commands are asynchronous, I recommend changing to a custom command and adding alias to preserve the result during the intermediate actions

Cypress.Commands.add('getVals', () => {
  cy.get('[id="22"] span')
    .then($els => {
      const vals = [...$els].map(el => el.innerText)
      return vals                    // vals is Cypress "subject" 
    })
}

cy.getVals().as('vals1')

// perform action on the page

cy.getVals().then(vals2 => {         // use then to obtain vals
  cy.get('@vals1').then(vals1 => {   // retrieve first from alias
    // compare
    expect(vals1).to.deep.eq(vals2)
  })
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文