我正在尝试迭代一个表并提取一个值,如果它在带有cypress的表中找到了它旁边的值

问题描述 投票:0回答:1

我正在尝试迭代一个表并将其值提取到一个变量中并在另一个字段中使用它

要素如下

  <tbody>
   <tr class>
     <td class="text-left">Transaction Type </td>
     <td class="text-left">0 </td>
   </tr>
   <tr class>
     <td class="text-left">STAN </td>
     <td class="text-left">009466 </td>
   </tr>

我想在找到 STAN 值时提取数值,并且正在使用此代码

  cy.get('tbody tr').each(($el) => {
    cy.wrap($el).within(() => {
      cy.get('td').eq(1).should('contain.text', 'STAN') // contains() doesn't work
    })
  })

我使用了以下脚本,但它失败了,我知道它还没有完成。请有人帮我找到 STAN 并将其值提取到变量中。

cypress
1个回答
0
投票

如果你确定“STAN”在表中,你可以直接找到它,无需迭代。

cy.contains('tbody tr', 'STAN')     // get the row with "STAN"
  .find('td').eq(1)                 // it's second column
  .then($el => {
    const text = $el.text()         // extract the text
    const trimmed = text.trim()     // remove the space at the end
    return trimmed
  })
  .as('myValue')                    // save it to an alias  
  .should('eq', '009466')           // just for proof (you may not know the value)

// later in the test
cy.get('@myValue').then(value => {
  ...
})

enter image description here


在您的示例 HTML 中,值后面有一个空格,因此我使用

text.trim()
将其删除。如果没有
.trim()
,您可能会因不间断空格 (
&nbsp;
) 而收到错误,例如

cy.contains('tbody tr', 'STAN')
  .find('td')
  .eq(1)
  .invoke('text')
  .as('myValue')                  // save to alias  
  .should('eq', '009466')

enter image description here


如果“STAN”可能不存在怎么办

在完美的测试中,您将使用

cy.intercept()
设置表数据,这样您就知道“STAN”在表中。

但如果由于某种原因无法做到这一点,您可以先检查:

cy.wrap(undefined).as('myValue')             // set up initial alias as undefined

cy.get('tbody tr' )
  .then($rows => {
    const rowWithSTAN = $rows.has('td:contains(STAN)')  // non-failing query
    if (rowWithSTAN.length) {                            // check the result

      cy.wrap(rowWithSTAN)                         // as per above example
        .find('td')
        .eq(1)
        .then($el => {
          const text = $el.text()     
          const trimmed = text.trim() 
          return trimmed
        })
        .as('myValue')                  
        .should('eq', '009466')
    }
  })
  
// later in the test
cy.get('@myValue').then(value => {
  if (value) {
    // only if not undefined
  }
})

$rows.has('td:contains(STAN)')
表示 - 过滤行以仅获取文本中包含
<td>
的行。

© www.soinside.com 2019 - 2024. All rights reserved.