【发布时间】:2022-09-29 20:06:08
【问题描述】:
我可以用cy.contains(\'hello\')检查cypress中是否存在文本,但是现在我从页面中删除了hello,我想检查hello不存在,我该怎么做cy.notContains(\'hello\')之类的事情?
标签: javascript cypress matcher
我可以用cy.contains(\'hello\')检查cypress中是否存在文本,但是现在我从页面中删除了hello,我想检查hello不存在,我该怎么做cy.notContains(\'hello\')之类的事情?
标签: javascript cypress matcher
对于不存在检查“你好”的简单问题,您可以使用.contain('hello') 后跟.should()。所以整个页面看起来像这样:
// code to delete hello
cy.contains('.selector', 'hello').should('not.exist')
或者您可以将其进一步缩小到应用程序的特定区域:
// code to delete hello
cy.get('.element-had-hello').should('not.include.text', 'hello')
【讨论】:
cy.contains('hello').should('not.exist) 如果出现不止一次的“你好”,将无法正常工作。
您可能更愿意检查实际元素实例是否已从 DOM 中删除
cy.contains('hello')
.then($el => {
// delete the element
cy.wrap($el)
.should($el => {
// has this element been removed?
expect(Cypress.dom.isAttached($el)).to.eq(false)
})
})
【讨论】:
cy.getByData('success-msg').contains('falsy').then($el => { cy.wrap($el).should($el => { expect(Cypress.dom.isAttached($el)).to.eq(false) }) })。它会查找falsy,如果不存在正确的,它会抛出一个带有 4000 毫秒超时的断言错误。原因可能是未达到的错误then。
您可以将contains 与选择器和文本结合使用。首先检查它是否存在,然后在删除检查后,它不存在。
cy.contains('selector', 'hello').should('exist')
//Actions to perform Deletion
cy.contains('selector', 'hello').should('not.exist')
【讨论】:
我更喜欢与现有答案略有不同的语法:
cy.root().should('not.contain.html', '<b>Fatal error</b>');
在这里你可以使用not.contain.html 来搜索html,或者not.contain.text 来搜索文本,例如测试一个PHP 应用程序,我使用
Cypress.Commands.add('visit2', (url, options) => {
const ret = cy.visit(url, options);
cy.root()
.should('not.contain.html', '<b>Fatal error</b>') // <b>Fatal error</b>: Uncaught ArgumentCountError: strlen() expects exactly 1 argument, 0 given
.should('not.contain.html', '<b>Warning</b>') // <b>Warning</b>: Cannot modify header information - headers already sent by (output started at /in/tbUXQ:4) in <b>/in/tbUXQ</b> on line <b>4</b><br />
.should('not.contain.html', '<b>Notice</b>') // <b>Notice</b>: Undefined variable: a in <b>/in/tbUXQ</b> on line <b>4</b><br /> cy.should('not.contain', '<b>Parse error</b>'); // <b>Parse error</b>: syntax error, unexpected '}' in <b>/in/tbUXQ</b> on line <b>4</b><br />
.should('not.contain.html', '<b>Parse error</b>'); // <b>Parse error</b>: syntax error, unexpected '}' in <b>/in/tbUXQ</b> on line <b>4</b><br />
return ret;
});
检测常见的 PHP 应用程序错误
【讨论】: