Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two DOM elements using Cypress?

Tags:

cypress

I'm trying to check if a contenteditable element is focused (it has the blinking caret), but this doesn't work:

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

What should I do instead?

like image 551
nachocab Avatar asked Jan 28 '23 04:01

nachocab


2 Answers

Using .then() will give you an element wrapped by jQuery. The wrappers are not equal, but the elements are:

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

I also replaced .then() with .should(). .should() is similar to .then(), except it will retry any contained assertions until they succeed or time out.

The code above is adapted from this jQuery answer.

like image 148
Joshua Wade Avatar answered Mar 15 '23 02:03

Joshua Wade


I think this will do what you want. If you want to assert anything else about it you can add an .and() after the .should() to chain assertions.

  cy.focused().should('have.attr', 'contenteditable', 'true');
like image 26
Brendan Avatar answered Mar 15 '23 04:03

Brendan