Search code examples
javascriptunit-testingtestingcypress

Cypress avoid waiting for background image loading


I am writing a test for a login page:

cy.visit(loginUrl);
//   type username and password
cy.get('#user').type(email);
cy.get('#password').type(password);
cy.get('#submit').click();

But I can see even though the text boxes are visible, cypress does not start the test until the background image is loaded. The background image is a bit bulky which takes time to load and hence test has to wait long to finish the login.

How can I make Cypress to not wait for the background image to load and start typing if the text boxes are available?


Solution

  • Stub the background image with an intercept.

    If I make a sample site that displays a large nasa image:
    https://images-assets.nasa.gov/image/PIA15985/PIA15985~orig.jpg it takes about 2 second to load.

    <body>
      <img src="https://images-assets.nasa.gov/image/PIA15985/PIA15985~orig.jpg" />
    </body>
    
    cy.viewport(1500,2000)
    
    Cypress.automation('remote:debugger:protocol', {
      command: 'Network.clearBrowserCache',
    })
    
    const start = Date.now()
    cy.visit(url).then(() => {
      expect(Date.now() - start).to.be.greaterThan(1500)
    })
    

    enter image description here


    Adding an intercept with fixture, loading off local disc it takes about 200ms.

    cy.viewport(1500,2000)
    
    Cypress.automation('remote:debugger:protocol', {
      command: 'Network.clearBrowserCache',
    })
    
    cy.intercept(/PIA15985~orig.jpg/, {fixture: '2560x12932.svg'})
    
    const start = Date.now()
    cy.visit(url).then(() => {
      expect(Date.now() - start).to.be.lessThan(500)
    })
    

    enter image description here