DEV Community

Dennis Zhang
Dennis Zhang

Posted on • Updated on

cypress查找元素

cy.get('.item') // 这会返回所有 class 为 'item' 的元素
cy.get('.item').eq(1) // 获取第二个 'item' 元素
cy.get('.item').eq(1).should('contain', 'Item 2') // 检查第二个 .item 元素是否包含文本 "Item 2"。

// .invoke('text') 方法来获取元素内的文本
cy.get('.item').eq(1).invoke('text').then((text) => {
  // 此时 text 包含了第二个 .item 元素的文本,即 'Item 2' 
  cy.log(text); // 在 Cypress 的日志中显示获取的文本
});


cy.get('.item').eq(1).invoke('text').should('eq', 'Item 2');
// 这会检查第二个 item 元素的文本是否正好等于 "Item 2"。

// 链式调用,确保后续的操作依赖于 then() 回调的结果,应该继续在 then() 内部链式操作。这样可以确保代码按预期顺序执行。


cy.get('selector').then(($el) => {
  const text = $el.text(); // 获取文本
  cy.log(text);            // 打印文本
  return text;             // 返回文本以继续链式调用
}).then((text) => {
  // 你可以在这里使用 text 进行操作
  cy.get('xxx').should('be.visible');  // 获取另一个元素并验证可见性
});


Cypress.Commands.add('getIframe', (iframeSelector) => {
  return cy.get(iframeSelector)
    .its('0.contentDocument.body')  // 进入 iframe 的 body
    .should('not.be.empty')         // 确保 iframe 内部不为空
    .then(cy.wrap);                 // 将其包装为 Cypress 命令链的一部分
});

// 使用自定义命令获取 iframe 内的元素
cy.getIframe('iframe#myIframe')      // 获取 iframe
  .find('button#myButton')           // 查找 iframe 内的元素
  .click();                          // 对找到的元素进行操作

Enter fullscreen mode Exit fullscreen mode

Top comments (0)