Search code examples
javascriptapigetxmlhttprequestcypress

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.


Solution

  • 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)