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?
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 => {
...
})
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
})
})
})