[go: up one dir, main page]

Features
< Back to Blog Overview

What's new in Selenium 4

2021-11-09
Selenium 4: what's new
  • Share on Facebook
  • Share on Twitter
  • Share on LinkedIn
  • Share on HackerNews

Selenium 4 has been released on October 13, 2021 and it's packed with exciting new features and improvements.


TestingBot is fully compatible with Selenium 4. Simply pass in a selenium-version: "4.0" capability and you'll be using SE4 with TestingBot for your tests.


What's new in Selenium 4?

After a long period of alpha and beta releases, the new Selenium 4 release comes with some exciting features for developers and testers, such as:


Relative Locators

Relative Locators is a feature which allows you to identify DOM elements in (a visual) relationship to other DOM elements.
You can use a more natural syntax in your tests, such as:

  • above
  • below
  • left of
  • right of
  • near

Internally, this uses the getBoundingClientRect() javascript call, to find relative elements.


One important note is to be careful when using this approach with responsive designs, as changing the viewport might re-order DOM elements relative to each other, breaking your test.
For example, two buttons might be next to each other in a desktop view, but might be stacked on top of each other in a mobile responsive view.


Print Page support

You now print a webpage as a PDF, available in Chrome, Edge and Firefox browsers.


This feature is similar to wkhtmltopdf or using Puppeteer/Playwright's PDF support.


You can pass in various options to customise the PDF generating, such as page size, margins, background and more.


Full Page and Element Screenshots

For Firefox, a feature has been added to take screenshots of the entire page, not just the viewport.


Next to this, there's a new method called getScreenshotAs for WebElements, which allows you to take a screenshot of a particular DOM element.


This feature is important when you want to do visual comparison testing. You are now able to test if an element on your page still matches a previous screenshot of the same element.


To use this feature, please see the example below, where we take a screenshot of a button on a page.

Copy code
@Test
public void takeElementScreenshot() {
	WebElement websiteLogo = driver.findElement(By.className("website-logo"));

	File source = elementLogo.getScreenshotAs(OutputType.FILE);
	File dest = new File(System.getProperty("user.dir") + "/screenshots/websiteLogo.png");

	try {
		FileHandler.copy(source, dest);
	} catch (IOException exception) {
		exception.printStackTrace();
	}
}

This snippet of code will find an element with className=website-logo, take a screenshot and save it in a file on your local computer.


CDP Commands

Selenium 4 now offers the possibility use the CDP (Chrome DevTools Protocol). You can use various CDP settings, for example to modify network conditions during your tests. Important: this is only available for Chrome and Edge browsers.


There's a new ChromiumDriver class which exposes two methods: getDevTools() and executeCdpCommand().


You can use this feature to capture requests and responses, block specific URLs (for example ad requests), mock network responses and control network speed (simulate slow websites).


Various network settings are available, such as:

  • network latency
  • upstream/downstream throughput
  • toggle offline-mode

Because Selenium 4 now exposes all CDP functionality, you can basically send and receive any kind of CDP message. Please see some examples below.

Overriding Device Metrics


For example, you can use the following CDP function to set device metrics in your Selenium 4 test:
Copy code
import org.openqa.selenium.devtools.DevTools;
DevTools devTools = driver.getDevTools();
devTools.createSession();
Map deviceMetrics = new HashMap()
{{
	put("width", 400);
	put("height", 6000);
	put("mobile", true);
	put("deviceScaleFactor", 50);
}};
driver.executeCdpCommand("Emulation.setDeviceMetricsOverride", deviceMetrics);

This will open a Chromium browser which will render the page with the deviceMetrics you specified.


Mocking Geolocation

Another useful CDP method is mocking geolocation with Emulation.setGeolocationOverride.
This allows you to test various conditions that depend on a user's geolocation, for example date/time formats, taxation rules, currencies, and other localized content.

Copy code
import org.openqa.selenium.devtools.DevTools;
DevTools devTools = driver.getDevTools();
devTools.createSession();
devTools.send(Emulation.setGeolocationOverride(
	Optional.of(28.385233),
	Optional.of(-81.563873),
	Optional.of(100))
);
driver.get("https://www.iplocation.net/");

Basic Authentication

This is a frequently requested feature: being able to specify a username and password for basic authentication protected webpages.
Previously, a test had to either specify the username and password in the URL (if supported by the browser) or use a third-party proxy.


Now you can use the CDP command Network.setExtraHTTPHeaders() which allows you to set extra headers for a specific request.

Copy code
import org.openqa.selenium.devtools.DevTools;
import org.openqa.selenium.devtools.network.Network;
import org.openqa.selenium.devtools.network.model.Headers;

DevTools devTools = driver.getDevTools();
devTools.createSession();
Map<string object> headers = new HashMap<>();
String basicAuth = "Basic " + new String(new Base64().encode(String.format("%s:%s", USERNAME, PASSWORD).getBytes()));
headers.put("Authorization", basicAuth);
chromeDevTools.send(Network.setExtraHTTPHeaders(new Headers(headers)));</string>

Improved Window Handling

Selenium 4 offers new functionality when it comes to handing windows and tabs in your tests.


A test can now go full-screen during a test, and have better control over opening tabs and new windows.


For example, to open a new tab, you can now do:

Copy code
driver.switchTo().newWindow(WindowType.TAB);

You can loop over all window handles, and switch to the window you want.

Copy code
for (String windowHandle : driver.getWindowHandles()) {
	if (originalWindow.contentEquals(windowHandle)) {
		driver.switchTo().window(originalWindow);
	}
}

Selenium IDE

Selenium IDE comes with a new UI and some new features, including:

  • A plugin system
  • A new CLI runner called "selenium-side-runner" which allows you to run previously recorded tests.
  • New control flow mechanisms to helps users write better tests, you can use "if", "else" and "while" functionality.
  • Multiple backup selectors are saved for each element lookup. If one lookup fails, the IDE can back up to another selector strategy.
  • Better code export to Java, C#, Python, Ruby and more.

There is also a plan to offer Selenium IDE as a standalone, Electron app.


Selenium Grid

Selenium Grid has been improved significantly. Users can now deploy a Grid, a Node and a Distributor. Some changes include:

  • Configuration is now saved in TOML files, making it easy to understand.
  • IPv6 support is now available.
  • HTTPs/TLS support is now available for Selenium grid.

The TestingBot Selenium grid is fully compatible with this new format. You can simply point your Selenium 4 tests to our Cloud Based Selenium grid and run your tests with Selenium 4.


To learn more about these new Selenium 4 feature on TestingBot, please see our Selenium 4 documentation which contains various examples.

TestingBot Logo

Sign up for a Free Trial

Start testing your apps with TestingBot.

No credit card required.

Other Articles

Automated Accessibility Testing with TestingBot

Automated Accessibility Testing allows you to test if your website is accessible to all types of users. The popular accessibility testing framew...

Read more
Puppeteer Testing in the Cloud

TestingBot has been providing a Selenium-based cloud service since 2012. We started with offering a Selenium RC compatible grid and added Selenium ...

Read more
Run Cypress tests on TestingBot's Browser Grid

TestingBot has released testingbot-cypress-cli, a CLI program that allows you to run your Cypress Automated tests on TestingBot's browser grid. Wh...

Read more
Run TestCafe tests on TestingBot's Browser Grid

Today we're releasing testcafe-browser-provider-testingbot, a plugin for TestCafe. TestCafe is a NodeJS framework to do automate end-to-end web t...

Read more
Selenium 4 (Alpha) Testing on TestingBot

TestingBot now supports Selenium 4 (Alpha) testing on its Selenium grid! Even though Selenium 4 is still only available as an alpha version, we've...

Read more
Test on macOS Big Sur and Safari 14

macOS Big Sur Preview 1 We have added Apple's upcoming OS to our list of platforms. Apple announced this next new major macOS release in its lates...

Read more