Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
How do I return the response from a cy.request through a function

I am trying to pass the result of an API request using the following function:

Add(someName)
    {
        cy.request ({
            method: 'POST',
            url: someURL,
            body: {
                name: someName
            }
        }).then(function(response){
            return response
        })
    }

When I try to call this function however, it does not give me the content of the response (it gives me Undefined). I thought this probably has something to do with either asynchronosity (if that is a word),or the scope of the object and therefore tried aliasing the response or defining an object outside of the function (then assigning the response to that object), without any luck.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You just need a return on the cy.request() call.

Add(someName) {
  return cy.request ({...})
    .then(function(response) {
      return response.body      // maps the response to it's body
    })                         // so return value of function is response.body 
}

The return value type is a Chainer (the same type as all Cypress commands) so you must use a .then() on it

myPO.Add('myName').then(body => ...

You don't need .then() after cy.request()

If you want the full response,

Add(someName) {
  return cy.request ({...})    // don't need a .then() after this 
                              // to return full response
}

How to await the result

If you want to await the result, use a Cypress.Promise as shown here

Add(someName) {
  return new Cypress.Promise((resolve, reject) => {
    cy.request ({...})
      .then(response => resolve(response))
  })
}

Awaiting

const response = await myPO.Add('myName')
about 4 years ago · Juan Pablo Isaza Report

0

You should try returning something in your function:

Add(someName)
{
    return cy.request ({
        method: 'POST',
        url: someURL,
        body: {
            name: someName
        }
    }).then(function(response){
        return response
    })
}

And then get the value returned:

Add('val').then((data) => {console.log(data)})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!