首页 > 解决方案 > 如何通过数组比较两个元素的文本内容

问题描述

我需要比较两个不同的元素是否包含相同的文本。案例:我有 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()。然后我尝试使用另一个并使用 secondElement.text() 创建一个 const,但效果不佳。

如果您有任何想法,请告诉我。

谢谢

标签: javascriptautomated-testscypress

解决方案


将比较包装在一个函数中,然后为每个按钮调用它

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

推荐阅读