我在用RegEx断言Cypress中的按钮文本时遇到问题(我需要一个精确匹配(。
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线程,但它似乎对我不起作用。
我得到了AssertionError
。
Timed out retrying after 4000ms: expected '<button>' to contain /^Nexto$/gi
当我手动放置字符串Nexto
时,它就通过了。
提前感谢您的建议!
在文档中断言-Chai
include(value(别名:contain,includes,contains
expect([1,2,3](.to.include(2(
(此处为include
下的chai文档中的更多详细信息(。
当用作.should('contain', ...)
时,它用于包含数组或对象,但不用于包含字符串。
精确匹配文本的一种方法是从元素中提取文本,并使用eq
、
const forwardButtonText = 'Nexto';
cy.get('button[data-test-key=forward-button]')
.invoke('text')
.then(text => text.toLowerCase())
.should('eq', forwardButtonText.toLowerCase())
或使用评论中提到的Cypress.contains()
cy.get('button[data-test-key=forward-button]')
.contains(new RegExp(`^${forwardButtonText}$`, 'gi'))