Skip to content
Advertisement

Cypress: Using cy.intercept() to check if a call hasnt been made yet?

Using cy.intercept() to intercept (and stub) a couple of network requests (to google tag manager), but would like to test at an early point in my test before I expect them to be called.

How would I test that the 2 routes I’m intercepting haven’t been called yet?

Thanks!

Advertisement

Answer

Intercept has a routeHandler section which can be a function

cy.intercept(routeMatcher, routeHandler?)

routeHandler (string | object | Function | StaticResponse)

The function receives the request, and inside that another function can receive the response,
see Intercepting a response

cy.intercept('/integrations', (req) => {
  // req.continue() with a callback will send the request to the destination server
  req.continue((res) => {
    // 'res' represents the real destination response
    // you can manipulate 'res' before it's sent to the browser
  })
})

so either on the receipt of req or the inner function on receipt of res, set an external flag and test it at one or more places in the test,

// top of the test

let interceptFlag = false;

cy.intercept('/my-route', (req) => {
  interceptFlag = true;
  req.continue((res) => {
    // or here
    interceptFlag = true;
  })
})

// later in the test

cy.wrap(interceptFlag).should('eq', false);   // not yet intercepted

// something triggers the API call

cy.wrap(interceptFlag).should('eq', true);    // now is intercepted

This is very generalized, if you post some details can be more specific.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement