简体   繁体   中英

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

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) => { ... });

You may have the same issue as here Cypress intercept() fails when the.network call has parameters with '/' .

In fact it's not "/" that causes the issue but the parameter section (anything after ? ), it would be considered as part of the URL.

As per reference question, use a regex or pathname instead of url (default).

cy.intercept('GET', /\/accountApplication\/getApplicationInfo/, req => {

or with pathname, parameters are excluded from the match

cy.intercept({method:'GET', pathname: `**/accountApplication/getApplicationInfo`}, req => {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM