我的脚本如下所示
const item ["a1", "a2",..............,"a45"]
const regex = new RegExp(`${item .join('|')}`, 'g')
if(cy.get('body').contains(regex)){
cy.get('body').then(($el) => {
if ($el.find('.button').length > 0) {
cy.get('.button2').then(($btn) => {
var infoo = $btn.text()
cy.writeFile('cypress/fixtures/test.txt', '\n', { flag: 'a+' })
cy.writeFile('cypress/fixtures/test.txt', infoo+' | ', { flag: 'a+' })
})
}
})
} // If
else {
cy.get('.button2')..click()
}
当其中一个单词在我的页面上可见时,我的脚本运行良好。如果不存在,它会崩溃并且脚本停止(因为这部分if(cy.get('body').contains(regex)){)。
我尝试了这个,但执行时间更长,因为下面的部分在另一个 for 循环中
const item ["a1", "a2",..............,"a45"]
const regex = new RegExp(`${item .join('|')}`, 'g')
for(let p = 1 ; p <= 45; p++) {
cy.get('body').then(($btn) => {
if($btn.text().includes(items[p - 1])){
cy.get('body').then(($el) => {
if ($el.find('.button').length > 0) {
cy.get('.button2').then(($btn) => {
var infoo = $btn.text()
cy.writeFile('cypress/fixtures/test.txt', '\n', { flag: 'a+' })
cy.writeFile('cypress/fixtures/test.txt', infoo+' | ', { flag: 'a+' })
})
}
})
} // If
})
当我使用带有正则表达式的包含时,我也收到此错误 “String.prototype.includes 的第一个参数不能是正则表达式”
我想节省时间并仅检查我的页面上是否出现一个项目。
错误说
这意味着您需要将参数更改为字符串(但这违背了您的目的)或更改为可以接受正则表达式的方法,例如
match()
或.test()
。例如
这个问题如何在 javascript 中使用 String.match()给出了一些如何
.match()
在 javascript 中使用的例子。