Search code examples
javascripthtmlcssiframecypress

wait for iframe to load with cypress


I'm testing an application that uses iframes, I wanted to know if with cypress it is possible to wait for an iframe to load, because I need to ensure that the iframe has been fully loaded to perform the test.

I tried using a cy.wait(), it even worked, however, setting a time on it makes my test very slow, since there are several use cases in this iframe


Solution

  • The package cypress-iframe has some built-in routines to wait for the iframe to load.

    From the source, it waits for the URL, ready state and load event:

    const hasNavigated = fullOpts.url
      ? () => typeof fullOpts.url === 'string'
                ? contentWindow.location.toString().includes(fullOpts.url)
                : fullOpts.url?.test(contentWindow.location.toString())
      : () => contentWindow.location.toString() !== 'about:blank'
    
    while (!hasNavigated()) {
      await sleep(100)
    }
    
    if (contentWindow.document.readyState === 'complete') {
      return $frame
    }
    
    await new Promise(resolve => {
      Cypress.$(contentWindow).on('load', resolve)
    })
    
    return $frame
    

    You can use that package directly without needing to implement your own wait strategy, but note the docs are a little out of date if you are using Cypress with version greater than 10.