【问题标题】:Can we test if element text includes text_ A or text_B with cypress?我们可以测试元素文本是否包含带有 cypress 的 text_A 或 text_B 吗?
【发布时间】:2019-10-08 13:42:08
【问题描述】:

只是想知道是否有一种方法可以使用 cypress 测试元素是否包含 text_A 或 text_B。例如,我有一个元素填充了从 API 请求返回的错误,我想检查错误消息是包含 text_A 还是 text_B。尝试了以下代码,但它仅在存在 text_A 时才有效,并且在返回 text_B 时失败。我没有收到任何来自赛普拉斯的无效语法错误,任何帮助都是赞赏。

 cy.get('body').then((body) => { 
     if (body.find('#request-error').length > 0) { 
         cy.get('#request-error').then((el)=> {
              assert.include(el.text(), ('text_A' || 'text_B')); 
         });
     } else {
         // DO SOMETHING ELSE
     }
 });

【问题讨论】:

  • 试试cy.get('#request-error').contains(/text_A|text_B/g),来自这个问题Cypress expect element to contain one string or another string
  • 嗨@Ackroydd 感谢您的回答。我设法使用您提供的链接中描述的想法使其工作。 const runout = ['text_A', 'text_B'] const regex = new RegExp(`${runout.join('|')}`) const text = el.text() expect(text).to.match(regex)
  • 还有一件事,您在.then((el) => ... 中执行此操作。你试过.contains(regex)吗?我从你对 Cory 的评论中注意到有一个子字符串因素,我想知道这种情况是否也适用于更简单的 .contains(regex)。

标签: javascript automated-tests cypress


【解决方案1】:

基本上你有一个可能的错误消息数组,所以你可以测试元素的文本是否存在于该数组中。

expect(['text_A', 'text_B']).to.include(el.text())

另一个更好的选择是使用.oneOf

expect(el.text()).to.be.oneOf(['text_A', 'text_B']);

https://docs.cypress.io/guides/references/assertions.html#BDD-Assertions

【讨论】:

  • 嗨科里,谢谢你的回答。但是我不认为这个解决方案可以应用于我的案例,因为我想要相反的; text_A 或 text_B 应包含在 el.text() 中。例如 el.text() = 'foo text_A bar' 或 el.text() = 'foo text_B bar'。试图切换参数并写道:expect(el.text()).to.include([text_A', 'text_B']) 但它失败并出现错误 AssertionError: expected 'foo text_A bar' to include ['text_A', 'text_B']
  • 啊,我明白了。很高兴看到您能够在 cmets 中获得有关您的问题的帮助!
【解决方案2】:

我迟到了,但你可以满足:

 cy.get('.text-element').invoke('text').then(text => {
      expect(text).to.satisfy((mText: string) => possibleMatchesArray.includes(mText));
 });

【讨论】:

    猜你喜欢
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 2022-01-14
    • 2012-08-21
    • 2021-04-26
    相关资源
    最近更新 更多