Warm tip: This article is reproduced from serverfault.com, please click

Not counting DOM elements in React site with Cypress?

发布于 2020-11-29 20:30:40

I can't count the number of DOM elements on a site written in React.

/// <reference types="cypress" />

context('Checking all components', () => {
    beforeEach(() => {
        cy.visit('https://news-israel.com');
    });

    it('Checking posts', () => {
        cy.get('.posts-wrapper').find('a').should('exist');
        cy.get('.posts-wrapper').find('a').its('length').should('be.gte', 100);
    });
});

In this case, it doesn't find the "a" tags because React rendering them asynchronously and dynamically. The "post-wrapper" class finds, followed by an exception:

The following error originated from your application code, not from Cypress. Cannot read property 'substr' of undefined When Cypress detects uncaught errors originating from your application it will automatically fail the current test.

How to correctly count the number of elements in this case, so that you can "wait for the elements"?

The site I'm testing is in production - https://news-israel.com

Questioner
SkyStar
Viewed
11
Hiram K. Hackenbacker 2020-11-30 06:33:42

The error is coming from the app itself, and ultimately should be fixed in the app source.

But see this note in the log

This behavior is configurable, and you can choose to turn this off by listening to the uncaught:exception event.

This links to an event handler you can use to debug. Add this to the top of the test to suppress the test failing when the error occurs.

Cypress.on('uncaught:exception', (err, runnable) => {
  // returning false here prevents Cypress from
  // failing the test
  return false
})

Now the test works, provide you use the correct class posts-wrapper not post-wrapper.


If you are able to fix the source, the error comes from the react-typed library, which is used in BreakingNews.js at line 75

<Typed
  strings={posts}
  typeSpeed={15}
  backSpeed={10}
  backDelay={5000}
  loop
/>

the posts variable is initially undefined, so you need a fallback value, e.g strings={posts || []}