cypressweb-api-testingautomation-testing

How to get POST API response in Cypress?


I am working on a project to automate using Cypress. In this project, I need to create an order for a patient. When I click on the submit button it will call the following API https://ibis-dev.droicelabs.us/api/dispenser/orders/ using the POST method and return one unique order that I want to get.

I have registered cy.intercept on top of my test like this:

cy.intercept({
    method: 'POST',
    url: 'https://ibis-dev.droicelabs.us/api/dispenser/orders/',
}).as('ordersCall')

And when the submit button is clicked I have used:

cy.clickOnElementUsingXpath(practicePageSelectors.submit_CreateOrderButton); // click on submit button
cy.wait('@ordersCall')
    .its('response.body')
    .then((body) => {
        // parsing might be not needed always, depends on the api response
        const bodyData = JSON.parse(body)
        cy.log(bodyData)
    })

But it returns the following error:

Timed out retrying after 5000ms: cy.wait() timed out waiting 5000ms for the 1st request to the route: ordersCall. No request ever occurred in cy.wait('@ordersCall')

Can anyone help me to get an orderID? Is there any other way to get the orderID?


Solution

  • After checking the provided images in the question comments, the error is as follows: Your intercept command in your Cypress test is waiting for requests to be made to your DEV environment, but looking at your last image from the console in the Cypress test runner your requests are being made to the QA environment.

    So you either have to adjust your Interceptor like this:

    cy.intercept({
        method: 'POST',
        url: 'https://ibis-qa.droicelabs.us/api/dispenser/orders/',
    }).as('ordersCall')
    

    or think about using relative paths for API calls to be independent from the environment:

    cy.intercept({
        method: 'POST',
        url: '/api/dispenser/orders/',
    }).as('ordersCall')