赛普拉斯获取属性值并存储在变量中

Meh*_*qat 7 automation cypress

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

就我而言,我想获取完整的类值并将其存储在变量中。

这段代码只给了我属性类值,但我如何将获取值存储在变量中

cy.get('div[class*="ui-growl-item-container ui-state-highlight ui-corner-all ui-shadow ui-growl-message"]').invoke('attr', 'class')
Run Code Online (Sandbox Code Playgroud)

小智 8

解决这种场景的一个好办法就是使用别名机制。人们可以利用这一功能将多个元素排入队列,然后通过链接结果来检查所有元素。我最近在 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)
  });
});

Run Code Online (Sandbox Code Playgroud)

Cypress 文档的变量和别名部分对此进行了描述。


Jos*_*djo 6

我试图将一个元素的样式与另一个元素进行比较,以确保它们相等。这是似乎对我有用的代码。

cy.get('.searchable-group-selector-card-image')
  .eq(4)
  .invoke('attr', 'style')
  .then(($style1) => {
    const style1 = $style1
  })
Run Code Online (Sandbox Code Playgroud)


Mr.*_* J. 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)
  })
Run Code Online (Sandbox Code Playgroud)

请注意,变量的范围位于大括号内。因此,使用变量必须在这些大括号内。