Search code examples
testingcodeceptionend-to-endcypress

What is equivalent for Codeception waitForElement method?


Codeception::waitForElement

I'm rewriting some tests from PHP based testing framework. I've a problem to detect new DOM elements fetched by Ajax POST request.

When I use:

cy.wait(timeout);

I'm able to fill text input loaded upon Ajax request, but this is an anti pattern.

I've also tried solution from: https://github.com/cypress-io/cypress/issues/937#issuecomment-345786498 - not working in my case.


Solution

  • You can simply use a cy.get() to wait for certain DOM elements to be rendered. Cypress will retry until the timeout is up:

    cy.get('.request-button').click()
    cy.get('.some-new-element', {timeout: 10000})
    // Cypress waits up to 10 seconds for element to appear
    cy.get('.new-button').click()
    // continue with test knowing the DOM has
    

    ...

    What if the new elements don't have a unique selector?

    Well then you've got a bigger problem, since you'll need to use selectors to perform actions on elements anyways.

    In this case, you can assert on text if it's nested anywhere inside an element using cy.contains():

    cy.contains('.common-class', 'new text', {timeout:10000})
    

    You cannot do this:

    cy.get('.common-class).contains('new text') 
    

    Because Cypress will not query the DOM again after a successful cy.get(), only watch the already found .common-class DOM node for changes.