Cypress期望元素包含一个字符串或另一个字符串。

18

我正在尝试进行一些Cypress断言,以查看它是否包含一个或另一个字符串。它可以是英语或西班牙语,因此任何一个都应该通过测试。

cy.get(el).should('contain', 'submit').or('contain', 'enviar')
显然不起作用。
  const runout = ['submit', 'enviar']
  const el = '[data-test=btn-submit]'
  function checkArray(arr, el) {
    for(let i = 0; i < arr.length; i++) {
      if(cy.get(el).contains(arr[i])) {
        return true
      } else {
        if (i === arr.length) {
          return false
        }
      }
    }
  }
  cy.expect(checkArray(runout,el)).to.be.true

未通过测试,但仍在检查两个字符串。

2个回答

25
你可以尝试正则表达式,参见contains#Regular-Expression
有关一些格式,请参见此问题Regular expression containing one word or another
我认为只需使用这个简单的表达式即可。
cy.get(el).contains(/submit|enviar/g)

先在Regex101或类似的在线测试工具上进行实验。

可以考虑使用以下方法构建它

const runout = ['submit', 'enviar']
const regex = new RegExp(`${runout.join('|')}`, 'g')
cy.get(el).contains(regex)

这在数字方面如何运作? - Nathan5x

1
也许这种方式可以检查“或”条件。我使用谷歌主页进行测试,并尝试在我的测试中找到“Google搜索”或“非Google搜索”。如果两者都找不到,将抛出错误。
describe('check if contains one of the text', function() 
{
it('Test google search button on google homepage',()=> {
    let url = 'https://www.google.com/';
    let word1 = 'Not Google Search';
    let word2 = 'Google Search';
    cy.visit(url);
    cy.get('input[value="Google Search"]').invoke('attr','value').then((text)=>{

        if (text=== word1) {
            console.log('found google not search');
        }
        else if (text === word2) {
            console.log('found google search');
        }
        else {
            console.log(text);
            throw ("cannot find any of them");
        }

    })
})
})

在上面的测试用例中,找到了word2,因此在控制台中记录了“Found google search”。

enter image description here


这确实可以工作,但只能在一定程度上。有时候 .get 会产生太多的文本,我无法指定更少的文本,这就是为什么需要使用 contains 的原因。 - nikclel
1
将if (text === word1)替换为if (text.includes(word1))怎么样?此外,您可以使用此函数编写自己的命令,并将word1、word2作为参数。 - Pigbrainflower

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