Alapan Das
Alapan Das

Reputation: 18586

Wait till the response body changes in Cypress

I am trying to automate a situation where I need to wait until in the response body I see the value Success. What I tried:

cy.server()
cy.route({
    method: 'GET',
    url: 'https://endpoint.com/api/readsomething'
    auth: {
        'username': username 
        'password': password
    },
    response: {}
}).as('checkStatus');

cy.wait('@checkStatus').then((ele) => {
expect(ele).should('have.property', 'response.body.latest_run.status', 'Success')
})
})

I am getting an error as: cy.wait() timed out waiting 5000ms for the 1st request to the route: checkStatus. No request ever occurred.

Would be great if you can let me know where I am doing wrong.

Upvotes: 2

Views: 3707

Answers (2)

Alapan Das
Alapan Das

Reputation: 18586

I was able to find the solution by looking into the request cypress doc - https://docs.cypress.io/api/commands/request.html#Request-Polling

Since the API endpoint I wanted to call was different from the application I was working on so I used cy.request() instead of cy.server() cy.route()

    function getStatus() {
        cy.request({
            method: 'GET',
            url: Cypress.config('endpoint'),
            auth: {
                'username': Cypress.config('username'),
                'password': Cypress.config('password')
            }
        }).then((response) => {
            if (response.body.status == "Success")
                return
            else
                getStatus()
        })
    }

    //Trigger the above function
    cy.then(getStatus)

Upvotes: 3

Joshua
Joshua

Reputation: 3186

You need to trigger an UI action. If the API requests are fired on page load, you will need to do cy.reload(), cy.visit() or click on a nav in order to make the requests happen. If it's something trigger by users' interactions. Like a button click, you will need to trigger that by cy.click() the button or something similar. And then wait for it.

Here is the real world example (simplified a bit) from our project:

cy.server();
cy.route({
  method: 'GET',
  url: 'api/pipelines',
  response: mockedData,
}).as('getPipelines');

cy.reload(); // Reload the page and so we can wait for until `@getPipelines` request is resolve
cy.wait('@getPipelines');

Upvotes: 1

Related Questions