Search code examples
cypresscypress-intercept

How to make Cypress test fail if it makes a request that does not have an intercept associated with it?


How to make Cypress test fail if it makes a request that does not have an intercept associated with it?

Let's say cypress navigates to a page and makes 10 requests. How can I make cypress automatically fail if any of those requests are not intercepted. I don't want any requests made from cypress to NOT be mocked.

Is this possible?


Solution

  • If you want to check the cy.intercept() coverage of app requests, add a middleware intercept.

    Generally you want the middleware to catch a broad range of URL's, for example all the API calls would be caught with

    cy.intercept('**/api/**/*')
    

    Middleware intercepts always see the captured calls first, and then pass them on to remaining intercepts.


    This example checks the GET calls during loading of https://cypress.io/.

    cy.intercept('https://www.cypress.io/_astro/**/*') // the intercept in my test
                                                       // want to check for unhandled calls
    
    // Middleware intercept - catches all calls
    const calls = []
    cy.intercept('https://www.cypress.io/**/*', { middleware: true }, (req) => {
      calls.push(req.url)
    }).as('all')
    
    cy.visit('https://cypress.io/')    // now visit the site
    
    cy.then(() => {
    
      // Use routes state info to compare handled calls vs all calls
      const handledUrls = Object.values(cy.state('routes'))
        .filter(route => route.alias !== 'all')
        .map(route => Object.values(route.requests)
          .map(interceptedRequest => interceptedRequest.request.url)
        })
        .flat()
    
      // Find the unhandled calls
      const unhandled = calls.filter(call => !handledUrls.includes(call))
      console.log('Unhandled calls: ', unhandled)
    
    })
    

    Logs two unhandled calls:

    [
      'https://www.cypress.io/cdn-cgi/scripts/5c5dd728/cloudflare-static/email-decode.min.js', 
      'https://www.cypress.io/videos/home_page.webm'
    ]