Cypress - jQuery
Cypress 和 jQuery
Section titled “Cypress 和 jQuery”Cypress 集成了 jQuery 并暴露了其方法,允许你在需要时使用 jQuery 进行 DOM 遍历或操作。虽然 Cypress 自身的命令(如 cy.get()、cy.contains() 等)通常更受青睐,因为它们具有重试能力并与测试运行器集成,但理解 jQuery 在 Cypress 中如何交互会很有益处。
Cypress 的 cy.get('selector') 命令查询 文档对象模型 (DOM) 并产出一个 jQuery 对象。然而,Cypress 命令是 异步 的,并被添加到命令队列中。而直接使用 jQuery 的调用(如 $('selector'))是 同步 的,它们在调用的确切时刻对 DOM 进行操作,不具备 Cypress 的重试能力。
在 Cypress 中访问 jQuery
Section titled “在 Cypress 中访问 jQuery”cy.get()的主体 (Subject): 当cy.get()解析后,它会生成一个 jQuery 对象作为主体。你可以使用.then()来直接处理这个对象。Cypress.$(): 你可以使用Cypress.$('selector')来利用 jQuery 同步地查询 DOM。这对于需要立即访问元素,且不涉及 Cypress 命令队列的情况很有用(例如,在自定义工具函数或复杂的.then()回调函数中)。
使用 .then() 调用 jQuery 方法
Section titled “使用 .then() 调用 jQuery 方法”Cypress 命令是 异步 的,并返回 Promise(尽管这主要由 Cypress 在内部管理)。当你想在通过 Cypress 获取的元素(其本身是一个 jQuery 对象)上使用 jQuery 方法,然后可能需要其返回值时,你通常会使用 .then() 命令。在 .then() 的 回调函数 内部,代码是 同步 执行的。
例如,要使用 jQuery 的 .text() 方法获取元素的文本内容:
describe('Tutorialspoint - jQuery Usage', () => { it('Should get text content using jQuery within .then()', () => { cy.visit('https://www.cypress.io'); // Example page
cy.get('h1') // Gets the first h1 element, yields a jQuery object .first() .then(($h1Element) => { // $h1Element is the jQuery object yielded by cy.get().first() const textContent = $h1Element.text(); cy.log('H1 Text:', textContent); expect(textContent).to.be.a('string').and.not.be.empty; }); });});**注意:**对于简单的文本断言,Cypress 提供了更直接的方法,例如 cy.get('h1').first().should('have.text', 'Expected Text') 或 .invoke('text').should('eq', 'Expected Text'),这些方法得益于 Cypress 的重试能力。
使用 Cypress.$()
Section titled “使用 Cypress.$()”Cypress.$() 提供了对 jQuery 的直接 同步 访问。这对于复杂的条件逻辑或在主 Cypress 命令链外部处理元素时非常有用。
describe('Tutorialspoint - Cypress.$ Example', () => { it('Should use Cypress.$ to interact with elements', () => { cy.visit('https://example.cypress.io/commands/querying');
cy.get('#query-btn').then(($button) => { // $button is a jQuery object from cy.get() // Let's say we want to find a sibling using Cypress.$ for demonstration const $sibling = Cypress.$($button).siblings('.query-list');
if ($sibling.length > 0) { cy.log('Found sibling with class .query-list'); expect($sibling.children().length).to.be.greaterThan(0); } else { cy.log('Sibling .query-list not found'); } }); });});关键注意事项
Section titled “关键注意事项”- 重试能力 (Retry-ability): 标准的 Cypress 命令(
cy.get()、cy.click()、断言)会自动重试,直到找到元素或断言通过(或超时)。直接的 jQuery 操作($()、Cypress.$())没有这种内置的重试能力。如果Cypress.$()调用时元素不存在,它会立即返回一个空的 jQuery 集合。 - 何时使用 jQuery: 对于大多数交互和断言,优先使用 Cypress 命令。在
.then()回调函数或Cypress.$()中使用 jQuery 方法,用于特定的 同步 操作、不易用 Cypress 命令表达的复杂 DOM 遍历,或者与需要 jQuery 对象的第三方库集成时。
理解这种区别有助于编写更健壮和可维护的 Cypress 测试。如果不确定,请优先使用 Cypress 内置的命令和断言。