Search code examples
node.jscypresscypress-intercept

Is there a way to intercept multiple requests linked by an "OR" conditional operator?


I am a beginner with cypress. I've been looking for a way to intercept API calls to at least one of multiple URLs. Let's say a button is clicked and something like this code is executed to check if a list of requests were called :

cy.get('@request1').should('have.been.called').log(`Request was made to 'REQUEST1_URL'`) 
OR 
cy.get('@request2').should('have.been.called').log(`Request was made to ''REQUEST2_URL'`)

I want to check if a request was sent to one url or the other, or both.

Has anyone encountered this problem before ? Any contribution is appreciated. Thanks.


Solution

  • The URL you use in the intercept should be general enough to catch both calls.

    For example if the calls have /api/ in common, this catches both

    cy.intercept('**/api/*')   // note wildcards in the URL
      .as('apiRequest')
    
    cy.visit('/')
    cy.wait('@apiRequest')
    

    If you have more paths in the url than you need to catch, for example /api/dogs/ /api/cats/ and /api/pigs/, then use a function to weed out the ones you want

    cy.intercept('**/api/*', (req) => {
      if (req.url.includes('dogs') || req.url.includes('cats') {   // no pigs
        req.alias = 'dogsOrCats'                                   // set alias
      }
    })
    
    cy.visit('/')
    cy.wait('@dogsOrCats')
    

    Catching 0, 1, or 2 URLs

    This is a bit tricky, if the number of calls isn't known then you have to know within what time frame they would be made.

    To catch requests which you are fired fairly quickly by the app

    let count = 0;
    cy.intercept('**/api/*', (req) => {
      count = count +1;
    })
    
    cy.visit('/')
    cy.wait(3000)   // wait to see if calls are fired
    cy.then(() => {
      cy.wrap(count).should('be.gt', 0)  // 0 calls fails, 1 or 2 passes
    })