Simulate slow responses with Cypress using cy.intercept()
Today I was trying to debug a flaky test that regularly breaks our jenkins pipeline. The fault appeared to be due to a randomly slow api response.
What I usually do is that I add a delay in my server to simulate the slow response and break the test, work my way to fix it and remove the delay in the server code.
But today, I didn't have any control over the server. I had to find out another way to do that.
Turns out it's quite easy with the Cypress intercept
command.
You can pass a req
as an argument to intercept the request, and from there use req.continue(response)
to change the response.
cy.intercept(
{
method: 'GET',
pathname: `_search`,
query: {
q: 'genera',
},
},
(req) => {
// do nothing with the req, only call the response with a 10s delay.
req.continue((res) => {
res.delay = 10000;
res.send();
});
},
).as('practitioner');