Is it possible in Cypress to send a request that won't reach the server but instead return a chosen response to us? I consider cy.intercept(), but does this function intercept the request that was sent to the server, along with the response from the server, which can then be modified?
Yes, there are various hooks that can be used for this purpose.
In the following example I use the before:response
to make a modification to the response.
To explore the way the hooks work, I use a win.fetch(...)
which creates the request independently of the application under test.
cy.intercept('/todos/*', (req) => {
req.on('before:response', (res) => {
// take a look at the actual server response
console.log('before:response', res.body)
// make a modification to that response
res.body.title = 'modified in before:response'
})
})
.as('todos')
// make a dummy call to your API to check the intercept is functional
cy.window().then(win => win.fetch('https://jsonplaceholder.typicode.com/todos/1'))
cy.wait('@todos')
.then(({request, response}) => {
// take a look at the modified server response
console.log('wait', response.body)
// should contain the changed data
expect(response.body.title).to.eq('modified in before:response')
})
You can see res modified tag in the Cypress log