我想获取Attribute值并将其存储在变量中,该如何在cypress中实现
对于我来说,我想获取完整的类值并将其存储在变量中。
这段代码只是给我属性类的值,但是如何将获取值存储在变量中
cy.get('div[class*="ui-growl-item-container ui-state-highlight ui-corner-all ui-shadow ui-growl-message"]').invoke('attr', 'class')
答案 0 :(得分:0)
最重要的是正确选择选择器,以便它精确地找到您要查找的值。在这种情况下,您已经找到了它。通过使用then()
,您可以将其存储在变量中。
cy.get('div[class*="ui-growl-item-container ui-state-highlight ui-corner-all ui-shadow ui-growl-message"]').invoke('attr', 'class')
.then($growl-message => {
const message = $growl-message.text()
//do the checks with the variable message. For example:
cy.contains(message)
})
请注意,变量的范围在大括号内。因此,使用该变量必须在大括号内。
答案 1 :(得分:0)
我试图将一个元素的样式与另一个元素的样式进行比较,以确保它们相等。这是似乎对我有用的代码。
cy.get('.searchable-group-selector-card-image').eq(4)
.invoke('attr', 'style').then(($style1) => {
const style1 = $style1
答案 2 :(得分:0)
解决这种情况的一个好方法是使用别名机制。可以利用此功能将多个元素排入队列,然后通过链接结果来检查所有元素。我最近遇到了一个 SPA 案例,其中断言必须发生在分布在不同角度路径(称为不同页面)的元素之间。
在您的用例中,这会是:
cy.get('.searchable-group-selector-card-image')
.eq(4)
.invoke('attr', 'style')
.as('style_1')
cy.get('.another-element')
.invoke('attr', 'style')
.as('style_2')
// later on for example you could do
cy.get('@style_1').then(style_1 => {
cy.get('@style_2').then(style_2 => {
// Both values are available and any kind of assertion can be performed
expect(style_1).to.include(style_2)
});
});
赛普拉斯文档的 Variables and Aliases 部分对此进行了描述。