Setting network conditions with Chrome and Edge

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

@Test
public void goOfflineWithChrome() throws IOException {
	String userName = System.getenv("SAUCE_USERNAME");
	String accessKey = System.getenv("SAUCE_ACCESS_KEY");
	URL gridUrl = new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub");
	ChromeOptions chromeOptions = new ChromeOptions();
	chromeOptions.setCapability("platformName", "Windows 10");
	chromeOptions.setCapability("browserVersion", "latest");

        Map<String, Object> sauceOptions = new HashMap<>();
	sauceOptions.put("name", "goOfflineWithChrome");
	sauceOptions.put("username", userName);
	sauceOptions.put("accessKey", accessKey);
	chromeOptions.setCapability("sauce:options", sauceOptions);

        RemoteWebDriver driver = new RemoteWebDriver(gridUrl, chromeOptions);

        WebDriver augmentedDriver = new Augmenter().augment(driver);
	ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();
	networkConditions.setOffline(true);
	((HasNetworkConditions) augmentedDriver).setNetworkConditions(networkConditions);

        try {
    	     driver.get("https://www.saucedemo.com");
    	     Assertions.fail("If Network is set to be offline, the previous line should throw      
            an exception");
	} catch (WebDriverException ex) {
    	    ((HasNetworkConditions) augmentedDriver).setNetworkConditions(new 
           ChromiumNetworkConditions());
	}
	driver.get("https://www.saucedemo.com");
	driver.quit();
}

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.





Written by

Diego Molina and Titus Fortner