Test Slow Network Conditions in Cypress by Throttling and Delaying Intercepted Requests

Filip Hric
InstructorFilip Hric

Share this video with your friends

Send Tweet
Published 3 months ago
Updated 3 months ago

When user waits too long, we might want to give them an option to reload page and try again. This is usually a hard case to reach and test effectively. But the .intercept() command provides us with a throttleKbps option that can limit the bandwidth, or we can use delay option that will delay our response for a given time.

Instructor: [0:00] With .intercept(), I can simulate different network conditions. For example, I can throttle my network speed and delayed my /api/boards request. To do that, I will type response throttleKB/s, and I can set that to a low value, so, for example, .05. When I now save my test, you can see that the response took much longer to come back from the server.

[0:31] Another way we can approach this is to give our response a delay. I'll type delay == 5 seconds. When I now save my test, you'll see that the boards are loading, and a message appears that it is taking too long. Let's test this message and write a test for this. I want to make sure that the element that is containing this text actually appears.

[1:00] I will copy the text and select my element using .contains() command. I want to make sure that this element is visible. Then I'll also make an assertion for the second text, which is the reload. Not only I want to make sure that it is visible, I want to click on it.

[1:23] Since Cypress will not click on something that is not visible, I can just type click(), and the assertion would be implicit. When I now save my test, I'll see that the assertion is passing. When I click on Reload, I again wait with the delay.

[1:41] To make sure that I intercept this command just once, I will change this first argument into an object and define the URL and then also the times attribute. I want to intercept this just once. When I now save my test, I can see that we click on the Reload button as soon as it is visible. Then the second time we load our page, we can see our boards immediately.