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