如何使用赛普拉斯比较两个 DOM 元素?

How to compare two DOM elements using Cypress?

我正在尝试检查 contenteditable 元素是否获得焦点(它有闪烁的插入符号),但这不起作用:

cy.get('span[contenteditable]').then($span => {
    cy.focused().then($focused => {
        expect($focused).to.eql($span)
    }
}

我应该怎么做?

我认为这会满足您的要求。如果你想断言关于它的任何其他内容,你可以在 .should() 之后添加一个 .and() 来链接断言。

  cy.focused().should('have.attr', 'contenteditable', 'true');

使用 .then() 会给你一个被 jQuery 包裹的元素。包装器不相等,但元素是:

cy.get('span[contenteditable]').should($span => {
    cy.focused().should($focused => {
        expect($focused[0]).to.eql($span[0]);
    }
}

我也用.should()替换了.then().should() 类似于 .then(),除了它会重试任何包含的断言,直到它们成功或超时。

以上代码改编自this jQuery answer

您的问题似乎是“如何使用 Cypress 测试元素是否聚焦?” (我偶然发现了这个问题,采用了与您相同的方法。)

Cypress added more explicit support for testing focus in 2019.

您现在可以简单地执行此操作:

cy.get('span[contenteditable]').should('have.focus');

类似但更简洁的解决方案
cy.get('span[contenteditable]').should($span => {
    cy.focused().should($focused => {
        expect($focused[0] === $span[0]), 'span is focussed').to.be.true;
    }
}

严格平等非常简单明了。 eql() 也可以工作,但会对每个 属性 进行深入比较。所以它实际上并不测试节点的身份。在实践中,这不会有什么不同。