Search code examples
cypresscypress-intercept

How to intercept POST request when multiple requests are being made in Cypress?


In my Cypress test, I am trying to intercept a request when logging in.

The password value I am passing to the request is 9K%bZKR8.

What I have observed is that when I click the login button, 2 POST requests are being made:

enter image description here

The 1st request contains the correct password 9K%bZKR8,

I have tried listening for this, but the test times out, saying No request ever occurred..

I even tried hard-coding the URL like below, but I keep getting the above error:

cy.intercept('POST', `**/Users/Login?username=****&password=9K%bZKR8`).as('LoginRequest')

The 2nd request for some reason contains a different password value - 9K%25bZKR8. I'm not sure where the 25 is coming from here.

I also hard-coded the URL here & it is being picked up somehow:

cy.intercept('POST', `**/Users/Login?username=****&password=9K%25bZKR8`).as('LoginRequest')

I could use the 2nd request & assert on that response, but I would have thought it is better to use the 1st request as that contains the correct password.

Can someone please tell me why the 2 requests are occuring, & how I can assert on the 1st one?


Solution

  • My theory is the %25 in 9K%25bZKR8 is the URL escape code for the literal char % in the typed-in string.

    See URL Encoding Functions - type in % and it gives back %25.

    To intercept, I would shorten the URL and use javascript inside the callback to match the query string section (i.e &password=9K%bZKR8)

    cy.intercept('POST', '**/Users/Login', (req) => {    // anything going to Login
      if (req.query.password === '9K%bZKR8') {
        req.continue(res => {
          console.log(res)        // check the response
        })
      if (req.query.password === '9K%25bZKR8') {
        req.continue(res => {
          console.log(res)        // check the response
        })
      }
    
    })