获取Cypress属性值并存储在变量中

11

我想获取属性值并将其存储在变量中,我们如何在Cypress中实现这一目标。

在我的情况下,我想获取完整的类值并将其存储在变量中。

这段代码只给出了属性类的值,但是我该如何将提取的值存储在变量中。

cy.get('div[class*="ui-growl-item-container ui-state-highlight ui-corner-all ui-shadow ui-growl-message"]').invoke('attr', 'class')
4个回答

8
解决这种情况的好方法是使用别名机制。可以利用此功能将多个元素排队,然后通过链接结果一起检查它们。最近我在SPA中遇到了一个案例,其中断言必须在不同的angular路由(称之为不同的页面)上分布的元素之间进行。

在您的用例中,这将会像:

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


这在Cypress文档的变量和别名部分中有描述。

这是错误的,你正在引入回调地狱。 - EugenSunic

8
我试图比较一个元素的样式和另一个元素的样式,以确保它们相等。以下代码似乎适合我使用。
cy.get('.searchable-group-selector-card-image')
  .eq(4)
  .invoke('attr', 'style')
  .then(($style1) => {
    const style1 = $style1
  })

2

以下是我获取带有文本“Eat”的标签中for属性值的方法。

cy.contains('Eat').then(($label) => {
    const id = $label.attr('for');
}

很好的、简洁的答案,对我有用。 - James Lee

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

请注意,变量的作用范围仅限于花括号内。因此,使用变量必须在这些花括号内部进行。

是的,我能够找到元素,并且接下来我想获取类属性值。我尝试了你的代码,但它报错了。 - Mehran Shafqat
这是错误和代码截图https://ibb.co/ysgbX2vhttps://ibb.co/N1Mv1Zp - Mehran Shafqat
那个问题有任何解决方案吗? - Mehran Shafqat
看起来我错过了最后一行的闭合括号。已将其添加到我的答案中。必须说,我现在意识到我并不完全确定这是否是正确的答案。使用 text() 将产生的对象 (cy.get('div[class*="ui-growl-item-container ui-state-highlight ui-corner-all ui-shadow ui-growl-message"]').invoke('attr', 'class')) 转换为字符串。但不知道那是否会保留类名。 - Mr. J.
我很担心这个问题。我不知道如何检索元素的类值解决方案。即使在谷歌上搜索也没有帮助。也许我们正在尝试解决一个可以绕过的问题,但我不知道实际目标是什么。我相信 https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html 可以帮助你找到这样的解决方法。 - Mr. J.
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接