如何通过数组比较两个元素的文本内容

3
我需要比较两个不同元素是否包含相同的文本。 案例: 我有5个不同的按钮时间段,假设它们是"日, 周, 月, 年, 十年" 每次当我点击特定的一个按钮时,我想比较下面图表中第二个元素的值是否也已更改且是否相同。
我的代码如下:
isAgregationBarChoosenValuePresent() {
        const selectors = ['button[data-testid="period-button-DAY"]',
                           'button[data-testid="period-button-WEEK"]',
                           'button[data-testid="period-button-MONTH"]',
                           'button[data-testid="period-button-YEAR"]',
                           'button[data-testid="period-button-DECADE"]']
        selectors.forEach(($selector) => {
            cy.get($selector, { timeout: 10000 }).eq(0).click().then($assertion => {
                const assertionText = $assertion.text()
                  return assertionText === cy.get('Second element).text()
})

我认为我不能使用cy.get('Second element').text()。我尝试使用另一个then并创建一个带有secondElement.text()的const,但这也不起作用。

如果您有任何想法,请让我知道。

谢谢

3个回答

2

将比较操作封装在一个函数中,然后为每个按钮调用该函数。

const compare = ($button, selector2) => {
  cy.get(selector2).then($selector2 => {
    expect($button.text()).to.eq($selector2.text())
  })
}

const selectors = ...
selectors.forEach((buttonSelector) => {
  cy.get(buttonSelector, { timeout: 10000 }).click()
    .then($button => compare($button, 'Second element'))

与DOM分离

有时,按钮元素在点击后可能会被替换(特别是React应用程序)。您可能会看到“与DOM分离”的错误。

在这种情况下,您需要在函数内重新查询按钮。

const compare = (buttonSelector, selector2) => {
  cy.get(buttonSelector).then($button => {
    cy.get(selector2).then($selector2 => {
      expect($button.text()).to.eq($selector2.text())
    })
  })
}

const selectors = ...
selectors.forEach((buttonSelector) => {
  cy.get(buttonSelector, { timeout: 10000 }).click()
    .then(() => compare(buttonSelector, 'Second element'))

谢谢,我使用了Alapan Das的解决方案,但从你的答案中我学到了新东西 :) - wojnarto

1
根据我对问题的理解,以下是你可以做的。
const selectors = [
  'button[data-testid="period-button-DAY"]',
  'button[data-testid="period-button-WEEK"]',
  'button[data-testid="period-button-MONTH"]',
  'button[data-testid="period-button-YEAR"]',
  'button[data-testid="period-button-DECADE"]',
]
selectors.forEach(($selector) => {
  cy.get($selector, { timeout: 10000 })
    .eq(0)
    .click()
    .then(($assertion) => {
      cy.get("Second element")
        .invoke("text")
        .then((secondText) => {
          if ($assertion.text() == secondText) {
            //Do Something
          } else {
            //Do something
          }
        })
    })
})

1
最近我刚把if else改成了expect($assertion.text()).to.equal(secondText)。 - wojnarto

0

谢谢大家,问题已经解决。


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