赛普拉斯测试中如何使用DOM中的值? [英] How to use values from DOM in cypress test?

查看:86
本文介绍了赛普拉斯测试中如何使用DOM中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的页面包含:

  <span data-testid="credit-balance">
    10
  </span>

在赛普拉斯中,如何将值提取到变量中以用于测试?

In Cypress, how do I extract the value to a variable to use in tests?

类似的东西:

const creditBalance = cy.get('[data-testid="credit-balance"]').value();

推荐答案

考虑使用 const var let 分配返回值使用赛普拉斯时的反模式.但是,当您发现自己想要这样做时,最好的做法是使用闭包来完成此操作.

Assigning return values with const, var, and let is considered an anti pattern while using Cypress. However, when you find yourself wanting to do so, is best practice to accomplish this with closures.

it("uses closures to reference dom element", () => {

   cy.get("[data-testid=credit-balance]").then(($span) => {

   // $span is the object that the previous command yielded

   const creditBalance = $span.text();

   cy.log(creditBalance);

  })

});

执行此操作的另一种方法是,如果您要存储和比较值或使用挂钩在测试之间共享值,请使用别名.

Another way to do this would be to use Aliases if you want to store and compare values or share values between tests using hooks.

it("aliasing the value from dom element", () => {

  cy.get("[data-testid=credit-balance]").as("creditBalance")

  cy.get("@creditBalance").should("contain", 10)

});

您如何实现这一点实际上取决于测试的目的.我建议您从文档中查看更多示例:尝试变量和别名最佳做法常见问题解答

How you approach this really depends on the objective of your test. I recommend checking out more examples from the documentation: try Variables and Aliases , Best Practices, and FAQ

这篇关于赛普拉斯测试中如何使用DOM中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆