Search code examples
cypresse2e

cypress use same endpoint with different response (testing http race condition)


I try to intercept two similar requests but two different responses in delay between each responses.

  1. send a first request to the /endpoint with delay in response like 3000ms
  2. second request to the same /endpoint with delay in response 1000ms

both requests have different response, something difficult to overwrite interceptor here

        cy.intercept('POST', '/validate', (req) => {
            req.reply({
                delay: 3000,
                fixture: 'invalidData.json'
            });
        })

        cy.intercept('POST', '/validate', (req) => {
            req.reply({
                delay: 1000,
                fixture: 'validData.json'
            });
        })

Solution

  • See Gleb Bahmutov's answer here
    Change fixture response in cypress for the same url with intercept

    Use the times option to restrict how many calls the intercept will catch.

    But note, the last added intercept is checked first so you probably need to reverse the order.

    cy.intercept({method: 'POST', url: '/validate', times: 1}, (req) => {
      req.reply({
        delay: 1000,
        fixture: 'validData.json'
      });
    })
    
    cy.intercept({method: 'POST', url: '/validate', times: 1}, (req) => {
      req.reply({
        delay: 3000,
        fixture: 'invalidData.json'
      });
    })
    

    Example app

    <script>
      setTimeout(() => {
        fetch('/validate', { method: 'POST'})
          .then(res => res.json())
          .then(res => console.log('1st', res))
      }, 100)
      setTimeout(() => {
        fetch('/validate', { method: 'POST'})
          .then(res => res.json())
          .then(res => console.log('2nd', res))
      }, 200)
    </script>
    

    Console outputs in expected order, with different fixture data

    2nd {data: 'valid'}
    1st {data: 'invalid'}