In this article, we will be stubbing a response with a JSON body onto the reqres site via the post method and retrieving the response.
it.only('Stub',()=>{
cy.visit('https://reqres.in/')
cy.intercept({
method: 'POST',
url: 'https://reqres.in/api/users',
middleware: false
},(req) => {
req.continue((res) => {
res.send({ "name":"JohnWick",
"job":"Assasin"
})
})
}).as('successfulAction')
cy.get("li[data-id='post']").click({force:true})
cy.wait(2000)
cy.xpath('//span[@class="url"]').click({force: true})
cy.wait('@successfulAction').then(($resp) => {
const acknowledgedDateTime = $resp.response.body
cy.log(acknowledgedDateTime)
})
})
- Using the intercept, we pass the URL for POST, and via the req callback object from intercept, we create another called res and send a JSON payload to our post method.
- Now clicking on the URL will trigger the intercept and post the payload.
- Ultimately, we ask the alias successfulAction to wait and then fetch the response body.
- We can see we are getting the response body we passed in.
- Log in to post comments