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

168
Views
How to save intercepted request body to outside variable

how can I save request body to outside variable. I want to do something like this:

let request;
  cy.intercept("POST", "/url**", ( req => {
    request = {...req.body};
    req.reply({
      body: response
    });
  }));

// use the "request" variable
// ...

and want to share this copied variable with other functions, but cy.intercept does not allow you to do this. Are there any workarounds?

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

0

You will need to add a wait to your code, since cy.intercept() is just a declarative event listener. Adding a wait for it's alias ensures that it has been triggered.

Also, since the code is async you will probably need to wrap and alias request to use it in other parts. Using the raw request variable might give you the empty value, depending on context.

Ideally you would do this in a beforeEach() I think. You probably also need to add the trigger for the POST call - is is a cy.visit()?

let request;

cy.intercept("POST", "**/url/**", ( req => {
  request = {...req.body};
  req.reply({
    body: response
  })
})).as('myIntercept')

// Must cy.wait (not cy.get) the first occurrence
cy.wait('@myIntercept') 

cy.wrap(request).as('myRequest')

// use the "request" variable
cy.get('@myRequest').then(request => {...    

or take request from the wait result

cy.intercept("POST", "**/url/**").as('myIntercept')

// Must cy.wait (not cy.get) the first occurrence
cy.wait('@myIntercept').its('request')
  .then(request => {
    ...
  })

// 2nd time use get()
cy.get('@myIntercept').its('request')
  .then(request => {
    ...
  })
about 4 years ago · Juan Pablo Isaza Report

0

You can use aliases for this.

let somevalue;

describe('Test Suite', () => {
  it('Test case', () => {
    cy.intercept("POST", "/url**").as('urlReq')

    cy.get('@urlReq').then((urlReq) => {
      // urlReq.body will have the intercepted request body
      somevalue = urlReq.body.key
    })
  })
})
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!