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.
1@Test2public void goOfflineWithChrome() throws IOException {3String userName = System.getenv("SAUCE_USERNAME");4String accessKey = System.getenv("SAUCE_ACCESS_KEY");5URL gridUrl = new URL("https://ondemand.us-west-1.saucelabs.com:443/wd/hub");6ChromeOptions chromeOptions = new ChromeOptions();7chromeOptions.setCapability("platformName", "Windows 10");8chromeOptions.setCapability("browserVersion", "latest");910Map<String, Object> sauceOptions = new HashMap<>();11sauceOptions.put("name", "goOfflineWithChrome");12sauceOptions.put("username", userName);13sauceOptions.put("accessKey", accessKey);14chromeOptions.setCapability("sauce:options", sauceOptions);1516RemoteWebDriver driver = new RemoteWebDriver(gridUrl, chromeOptions);1718WebDriver augmentedDriver = new Augmenter().augment(driver);19ChromiumNetworkConditions networkConditions = new ChromiumNetworkConditions();20networkConditions.setOffline(true);21((HasNetworkConditions) augmentedDriver).setNetworkConditions(networkConditions);2223try {24driver.get("https://www.saucedemo.com");25Assertions.fail("If Network is set to be offline, the previous line should throw26an exception");27} catch (WebDriverException ex) {28((HasNetworkConditions) augmentedDriver).setNetworkConditions(new29ChromiumNetworkConditions());30}31driver.get("https://www.saucedemo.com");32driver.quit();33}
This is how the test above looks when it is executed in Sauce Labs:
Check out our comprehensive guide to Selenium 4 for more information.