6

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?

Joshua Wade
  • 4,755
  • 2
  • 24
  • 44
nachocab
  • 13,328
  • 21
  • 91
  • 149

4 Answers4

7

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.

Joshua Wade
  • 4,755
  • 2
  • 24
  • 44
2

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');
Brendan
  • 4,327
  • 1
  • 23
  • 33
1

A similar but cleaner solution as https://stackoverflow.com/a/53233107/787333

cy.get('span[contenteditable]').should($span => {
    cy.focused().should($focused => {
        expect($focused[0] === $span[0]), 'span is focussed').to.be.true;
    }
}

Strict Equality is very simple and clean. eql() also works but does a deep comparison of every property. So it doesn't actually test identity of nodes. In practice this won't make a difference though.

Narretz
  • 4,769
  • 32
  • 40
0

The spirit of your question seems to be, "How do I test that an element is focused using Cypress?" (I stumbled upon this question taking the same approach you did.)

Cypress added more explicit support for testing focus in 2019.

You can now simply do this:

cy.get('span[contenteditable]').should('have.focus');
Derek
  • 827
  • 11
  • 23