首页 > 解决方案 > 赛普拉斯断言失败,包含方法的正则表达式

问题描述

我在 Cypress 中使用 RegEx 断言按钮文本时遇到了麻烦(我需要完全匹配)。

HTML

<button data-test-key="forward-button">Nexto</button>

JS

const forwardButtonText = 'Nexto';

cy.find('button[data-test-key=forward-button]')
  .should(
    'contain',
    new RegExp(`^${forwardButtonText}$`, 'gi'),
    );

我关注了这个SO thread,但它似乎对我不起作用。

我得到一个AssertionError.

Timed out retrying after 4000ms: expected '<button>' to contain /^Nexto$/gi

Nexto当我手动放置字符串时,它通过了。

提前感谢您的任何建议!

标签: regexcypress

解决方案


在文档中断言 - Chai

include(value) 别名:包含、包含、包含
expect([1,2,3]).to.include(2)

include (这里的柴文档中有更多详细信息)。

当用于.should('contain', ...)数组或对象包含时,而不是字符串包含。

精确匹配文本的一种方法是从元素中提取它并使用eq,

const forwardButtonText = 'Nexto';

cy.get('button[data-test-key=forward-button]')
  .invoke('text')
  .then(text => text.toLowerCase())
  .should('eq', forwardButtonText.toLowerCase())    

.contains()或使用评论中提到的赛普拉斯

cy.get('button[data-test-key=forward-button]')
  .contains(new RegExp(`^${forwardButtonText}$`, 'gi'))

推荐阅读