javascript - 如何通过数组比较两个元素的文本内容
问题描述
我需要比较两个不同的元素是否包含相同的文本。案例:我有 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,但效果不佳。
如果您有任何想法,请告诉我。
谢谢
解决方案
将比较包装在一个函数中,然后为每个按钮调用它
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'))
推荐阅读
- c# - 包含字典的 C# 复杂对象
XML反序列化问题 - c# - 使用 LDAP 和 C# 拒绝访问
- numeric - 仅在 qlikview 中获取数字值
- python - Python,Tensorflow ValueError:没有为任何变量提供梯度
- python - 如何在 Python 中使用 ssh-keygen ed25519 密钥进行加密?
- python - 导出 CSV 显示 ImportError: cannot import name 'CompressionOptions' from 'pandas._typing'
- postgresql - 在 Manjaro 上哪里可以找到 postgresql.log
- html - 标记html宽度溢出-y和fancybox滚动
- r - 用点分割线串并在 R 中分配新的段 ID
- android - Android Companion 设备配对:如何使用 REQUEST_COMPANION_RUN_IN_BACKGROUND 权限?