Back to Resources

Blog

Posted October 12, 2021

Setting Network Conditions with Chrome and Edge

quote

Selenium 4 exposes a set of utilities to modify the network conditions in Chromium based browsers, like Google Chrome and Microsoft Edge. It is possible to modify the network in the following ways:

  • Going offline

  • Setting a latency for the connection

  • Alter the upload or download throughput 

All these are extremely useful to test web applications under different network conditions. Here is an example in Java where the connection goes offline. For additional examples in multiple languages, look at our Selenium 4 Documentation.

Going offline

1
@Test
2
public void goOfflineWithChrome() throws IOException {
3
String userName = System.getenv("SAUCE_USERNAME");
4
String accessKey = System.getenv("SAUCE_ACCESS_KEY");
5
URL gridUrl = new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub");
6
ChromeOptions chromeOptions = new ChromeOptions();
7
chromeOptions.setCapability("platformName", "Windows 10");
8
chromeOptions.setCapability("browserVersion", "latest");
9
10
Map<String, Object> sauceOptions = new HashMap<>();
11
sauceOptions.put("name", "goOfflineWithChrome");
12
sauceOptions.put("username", userName);
13
sauceOptions.put("accessKey", accessKey);
14
chromeOptions.setCapability("sauce:options", sauceOptions);
15
16
RemoteWebDriver driver = new RemoteWebDriver(gridUrl, chromeOptions);
17
18
WebDriver augmentedDriver = new Augmenter().augment(driver);
19
ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
20
networkConditions.setOffline(true);
21
((HasNetworkConditions) augmentedDriver).setNetworkConditions(networkConditions);
22
23
try {
24
driver.get("https://www.saucedemo.com");
25
Assertions.fail("If Network is set to be offline, the previous line should throw
26
an exception");
27
} catch (WebDriverException ex) {
28
((HasNetworkConditions) augmentedDriver).setNetworkConditions(new
29
ChromiumNetworkConditions());
30
}
31
driver.get("https://www.saucedemo.com");
32
driver.quit();
33
}

This is how the test above looks when it is executed in Sauce Labs:

selenium 4 network conditions

Check out our comprehensive guide to Selenium 4 for more information.

Titus Fortner
Sr. Developer Experience Engineer, Sauce Labs
Diego Molina
Staff Software Engineer at Sauce Labs
Published:
Oct 12, 2021
Share this post
Copy Share Link
© 2023 Sauce Labs Inc., all rights reserved. SAUCE and SAUCE LABS are registered trademarks owned by Sauce Labs Inc. in the United States, EU, and may be registered in other jurisdictions.