Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Cypress not finding my H1 element?

I have some end to end tests targeting a website, implemented in Javascript using Cypress.io v3.2.0. One of my test steps is implemented like so:

cy.get('h1#feed_header_id').contains('אביזרי');  //('אביזרי' is in Hebrew)

When I run the test in the Cypress GUI, it fails on the CONTAINS step. But when I click on the CONTAINS step in the log, the snapshot clearly shows the H1 element with the text "אביזרי" in it.

Screenshot:

Please note: The element is: <h1 id="feed_header_id">אביזרי רכב</h1> and is the only element with this id in the page.

Why does Cypress fail to find the text in the element when the element and the text are clearly visible?

like image 233
urig Avatar asked Nov 16 '25 22:11

urig


1 Answers

You can use the alternate 'contains' command,

cy.contains('#feed_header_id', 'אביזרי');

The reason is that cy.get(...).contains(...) does not wait for async content.

The get() part has automatic retry, but the id selector is hard-coded in your html, so get() succeeds immediately (before the xhr returns it's value), then the element is tested for content (which is initially empty).

The alternate syntax above applies auto-retry to both the selector and the content.

Here is a quick test I used to ensure it is not due to RTL language features.

Spec - contains-rtl.js

describe('contains', () => {
  it('waits for content', () => {
    cy.visit('app/hebrew-calendar.html').then(x => console.log('x', x))
    // cy.get('h1#feed_header_id').contains('כ״ט בְּאִיָּר תשע״א');
    cy.contains('h1#feed_header_id', 'כ״ט בְּאִיָּר תשע״א');
  })
})

Sample page - hebrew-calendar.html

<h1 id="feed_header_id"></h1>

<script>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'https://www.hebcal.com/converter/?cfg=json&gy=2011&gm=6&gd=2&g2h=1', true);

  xhr.onload = function () {
    const hebrewDate = JSON.parse(xhr.response).hebrew;
    const el = document.querySelector('h1#feed_header_id');
    el.textContent = hebrewDate;
  };

  xhr.send(null);
</script>
like image 200
Richard Matsen Avatar answered Nov 18 '25 12:11

Richard Matsen