Search code examples
javascriptcypresse2e-testingcypress-intercept

How to read a response in Cypress?


I am trying to write an E2E test using Cypress 12.3 for a web application. During a certain part of the journey, the app makes a GET request to the endpoint "api/v2/accountApplication/getApplicationInfo?uuid=xxxxxxx". The response from this request includes a field called "abChoice.welcome" which has a value of either 'a' or 'b'. This value is used for A/B testing in my Vue app. The structure of the response is as follows:

{
    "resultStatus": true,
    "errorCode": 0,
    "errorMessage": null,
    "resultData": {
        "abChoice": {
            "welcome": "a"
        }
    }
}

I am trying to write a test that checks the response from this request and makes different assertions based on the value of "abChoice.welcome". I have attempted to use the cy.intercept command to check the response, but it is not working as expected. I also tried creating an alias for the request and using cy.wait(@myAliasName), but Cypress threw an error and said the request was never made, even though I can see the request in the logs.

describe('A/B testing', () => {
  it('shows A or B pages', () => {
    cy.intercept('GET', '**/accountApplication/getApplicationInfo', req => {
      const { body } = req
      cy.log(body)
      if (body.resultData.abChoice.wlecome === 'a') {
        cy.log('A')
        // assert something
      } else {
        cy.log('B')
        // assert something
      }
    })
  })
})

The log shows the following, so the request is definitely being made. (I've removed sensitive information)

(xhr)GET 200 /api/v2/xxxx/accountApplication/getApplicationInfo?uuid=xxxx

Solution

  • The reason your cy.wait() does not succeed and your validation is never run is because your intercept's request url is never matched. This is because your url does not include the query parameters.

    Assuming that the query parameter uuid is not relevant to your intercept, you could do something like the following, adding a wildcard onto the end of your existing url:

    cy.intercept('GET', '**/accountApplication/getApplicationInfo*', (req) => { ... });
    

    If uuid were relevant, you could simply attach it to the end of url matched on:

    cy.intercept('GET', '**/accountApplication/getApplicationInfo?uuid=*', (req) => { ... });
    

    If you weren't assured that uuid was going to be the first query parameter, you would need to update the "simple-string" url method to using a RouteMatcher.

    cy.intercept({ 
      pathname: '**/accountApplication/getApplicationInfo'
      query: {
        uuid: 'foo'
      },
      method: 'GET'
    }, (req) => { ... });