如果我的页面包含:
<span data-testid="credit-balance">
10
</span>
在 Cypress 中,如何将值提取到变量以在测试中使用?
大致如下:
const creditBalance = cy.get('[data-testid="credit-balance"]').value();
使用
const
、var
和 let
分配返回值被认为是使用 Cypress 时的反模式。
然而,当您发现自己想要这样做时,最好的做法是使用闭包来实现这一点。
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);
})
});
如果您想使用挂钩存储和比较值或在测试之间共享值,另一种方法是使用别名。
it("aliasing the value from dom element", () => {
cy.get("[data-testid=credit-balance]").as("creditBalance")
cy.get("@creditBalance").should("contain", 10)
});
如何处理这个问题实际上取决于您的测试目标。我建议查看文档中的更多示例:尝试 Variables and Aliases 、Best Practices 和 FAQ
如果您想检索该值并用它执行任何断言,也可以使用一种快速、有效的方法
.invoke
it('Getting the value and performing an assertion', () =>{
cy.get('selector').invoke('val').should('eq',10)
})
Cypress 文档有一个示例,说明如何比较两个元素的文本值
// will keep text from title element
let titleText
cy.get('.company-details')
.find('.title')
.then(($title) => {
// save text from the first element
titleText = $title.text(); //original uses normalizeText($title.text())
})
cy.get('.company-details')
.find('.identifier')
.should(($identifier) => {
// we can massage text before comparing
const idText = $identifier.text(); //original uses normalizeText($identifier.text())
// text from the title element should already be set
expect(idText, 'ID').to.equal(titleText)
})
如果您必须获取值而不是文本,请使用它。这对我有用。
<span data-testid="credit-balance" value='100'></span>
如上
cy.get('[data-testid="credit-balance"]')
.invoke("val")
.then(($amount) => {
// $span is the object that the previous command yielded
cy.log($amount);
});
您可以使用 JQuery 中的 prop() 并将其分配给 const 值和内部 if 块。
const value = cy.get('[data-testid="credit-balance"]').prop('name of the property');
prop() 将以字符串形式返回属性值