DEV Community

Raphaël Badia
Raphaël Badia

Posted on

2 2

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')
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (1)

Collapse
 
saurabhchauhan98 profile image
Saurabh Chauhan

Use res.setDelay(delay) instead

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay