Cypress - 文本验证
Cypress - 文本内容验证
Section titled “Cypress - 文本内容验证”验证 web 元素的文本内容是 UI(用户界面)测试的基本组成部分。Cypress 提供了几种获取和断言(assert)文本的方法,确保你的应用向用户显示正确的信息。
方法 1:使用 invoke('text') 和 expect
Section titled “方法 1:使用 invoke('text') 和 expect”你可以使用 invoke('text') 命令来获取 DOM(文档对象模型)元素的文本内容。这个命令会产生文本,然后你可以在一个 .then() 回调函数中使用断言库,例如 Chai(Cypress 内置),来执行验证。
使用 invoke('text') 的实现
Section titled “使用 invoke('text') 的实现”假设你想要验证页面上某个标题的文本:
describe('Text Verification Demo', () => { it('Scenario 1: Verifies text using invoke("text") and expect', () => { cy.visit('https://example.cypress.io/commands/querying');
// 获取主标题元素 cy.get('h1').first().invoke('text').then((actualText) => { // 'actualText' 变量现在持有字符串 "Querying" // 如有必要,最好修剪(trim)空白字符 const trimmedText = actualText.trim(); expect(trimmedText).to.equal('Querying'); // Chai 断言,用于精确匹配 expect(trimmedText).to.contain('Query'); // Chai 断言,用于部分匹配 }); });});在此示例中,invoke('text') 获取了文本内容。.then() 回调函数接收到这个文本,然后我们使用 Chai 的 expect 语法进行断言。如果你需要在断言之前对文本进行操作或执行复杂的逻辑,这种方法提供了灵活性。
方法 2:使用 Cypress 内置的 should 断言
Section titled “方法 2:使用 Cypress 内置的 should 断言”Cypress 使用 .should() 命令提供了强大的内置断言。这通常是直接验证文本内容更符合习惯且更简洁的方式。
使用 should 的常见文本断言:
Section titled “使用 should 的常见文本断言:”should('have.text', 'expected text'):断言元素的文本内容与expected text精确匹配。这会考虑完整的文本内容,包括子元素的文本。should('contain.text', 'partial text')或should('include.text', 'partial text'):断言元素的文本内容包含partial text。这对于检查子字符串是否存在很有用。should('match', /regex/):断言元素的文本内容匹配给定的正则表达式(regex)。
使用 should 断言的实现
Section titled “使用 should 断言的实现”describe('Text Verification Demo', () => { it('Scenario 2: Verifies text using .should() assertions', () => { cy.visit('https://example.cypress.io/commands/querying');
// 验证主标题的精确文本 cy.get('h1').first().should('have.text', 'Querying');
// 验证按钮的部分文本 // 假设存在一个 ID 为 'query-btn' 且文本为 'Submit Query Button' 的按钮 cy.get('#query-btn').should('contain.text', 'Button'); // 或者使用 include.text cy.get('#query-btn').should('include.text', 'Submit Query');
// 带有包含文本的更具体元素的示例 // 在 example.cypress.io/commands/assertions 页面上,有一个表格。 cy.visit('https://example.cypress.io/commands/assertions'); cy.get('.assertion-table td').first() // 获取断言表格中的第一个单元格 .should('have.text', 'Column content'); // 验证其精确文本 });});在 Cypress 中,通常优先使用 .should() 进行文本验证,因为它更简洁且与 Cypress 的重试(retry-ability)机制一致。Cypress 会自动重试断言直到通过或超时,这对于处理动态内容有帮助。
选择正确的方法
Section titled “选择正确的方法”- 对于精确文本匹配,使用
.should('have.text', ...)。 - 对于部分文本匹配,使用
.should('contain.text', ...)或.should('include.text', ...)。 - 当你需要在断言之前获取文本进行进一步处理(例如,解析、与另一个动态值比较)时,使用
.invoke('text').then(...)。
有效的文本验证对于确保 UI 的正确性至关重要。Cypress 提供了灵活而强大的工具来高效地完成此任务。有关更多断言选项,请参阅 Cypress 关于断言的文档以及内置的 Chai BDD(行为驱动开发)断言。