DEV Community

rangana dilhara
rangana dilhara

Posted on

Cypress Tests failing in Headless mode for API execution

I am developing an API testing backend using Cypress with cy.request. I am aware that cy.request natively uses built-in promises (Cypress.Chainable), so there is no need to handle it with JavaScript promises.

However, my requirement is to call test APIs with single calls, without chaining .then conditions.

Currently, my code works properly in Cypress UI mode. But in headless mode, the second request fails with the error: "Cypress test was stopped while running this command." I suspect the issue is related to JavaScript promise handling and asynchronous behavior.

Despite trying multiple solutions, I haven't been able to fix this issue. I need to make this work using a promise-based approach. Please help me or suggest a fix.

headless run command : npx cypress run --headless --spec 'pathtofile'

//following is the full working code with a public API

const newPet= {
    "name": "jkysssssss",
    "data": {
       "year": 2017,
       "price": 4589,
       "CPU model": "Intel eeeeeee",
       "Hard disk size": "1 TB"
    }
}


export function makeRequest(requestOptions :any) {
  return new Promise((resolve, reject) => {
      // Make the request using cy.request with the provided requestOptions
      cy.request(requestOptions).then((res) => {
          if (!res || !res.body) {
              return reject(new Error('No response body returned from request.'));
          }

          // Ensure response body is an object
          if (typeof res.body !== 'object' || res.body === null) {
              res.body = { data: res.body };
          }

          // Add status to the response
          res.body.status = res.status;

          // Log the response
          cy.log(JSON.stringify(res.body));

          // Resolve the promise with the response body
          resolve(res.body);
      })
  });
}


describe('API Tests', () => {
    it('should make a POST request and handle the response', async () => {
        const requestOptions = {
            method: 'POST',  // HTTP method
            url: 'https://api.restful-api.dev/objects',  // API URL
            headers: {
                'Content-Type': 'application/json',
            },
            body: newPet,
        };

   //request calls
   await  makeRequest(requestOptions).then((res :any)=>{
    expect(res.body.status).to.eq(200);
   });
await  makeRequest(requestOptions).then((res :any)=>{
    expect(res.body.status).to.eq(200);
   });

    });
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)