Home Guide How to Run Visual Tests with Selenium: Tutorial

How to Run Visual Tests with Selenium: Tutorial

By Neha Vaidya, Community Contributor -

Both manual and automated software testing has grown exponentially in the last few years. Among many testing tools, Selenium has been a global favorite for automation purposes, thanks to its many relevant offerings and functionalities.

Given its popularity, it is natural for testers to try running automated visual testing via Selenium. Visual testing verifies the software user interface (UI) appears correctly to all users. Visual tests check that each element on a web page appears in the right shape, size, and position. It also checks that these elements appear and function perfectly on a variety of devices and browsers.

This article explores how to code and run visual tests with Selenium WebDriver.

How to run Visual tests using Selenium?

Let’s start off by writing a simple login functionality Selenium test case. Since this test is created using the JUnit framework, refer to JUnit Tutorial before proceeding further.

Study the test case below:

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test; 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Loginex {

private WebDriver driver;

@Before
public void login() {
System.setProperty("webdriver.chrome.driver", "path of driver");
driver=new ChromeDriver();
driver.manage().window().maximize();

}

@Test
driver.get("https://www.browserstack.com/users/sign_in");
WebElement username=driver.findElement(By.id("user_email_Login"));
WebElement password=driver.findElement(By.id("user_password"));
WebElement login=driver.findElement(By.name("commit"));
username.sendKeys("abc@gmail.com");
password.sendKeys("your_password");
loginex.click();
String expectedUrl="https://live.browserstack.com/dashboard";
String actualUrl= driver.getCurrentUrl();
Assert.assertEquals(expectedUrl,actualUrl);
}
}

@After
public void teardown() {
driver.quit();
}

The code loads an instance of Chrome, visits the Browserstack login page, enters the username & password, submits the form, asserts the Expected and the Actual URL, and closes the browser.


A Must Read: Introduction to Visual Regression Testing


Now let’s explore how to perform visual testing with a tool called Percy.

Go to Percy by BrowserStack and click on Get started. In the dashboard, create a new project and name the project as shown below.

Selenium Visual Testing

How run visual tests with Selenium on Percy

Selenium Visual Testing Example

Now, create the code for the project and follow the steps below to integrate Percy.

1. Add percy-java-selenium to project dependencies.
For example, if using Maven for dependencies:

<dependency>
<groupId>io.percy</groupId>
<artifactId>percy-java-selenium</artifactId>
</dependency>

2. Install the @percy/agent npm package:

$ npm install --save-dev @percy/agent

3. Import the Percy selenium library into each file from which to take snapshots:

import io.percy.selenium.Percy

4. Create a new Percy object with a WebDriver instance as a parameter:

Percy percy = new Percy(webDriver);

5. Call percy.snapshot(SNAPSHOT_NAME) whenever a snapshot has to be generated.

6. Wrap the run command in ./node_modules/.bin/percy exec –. This will start a Percy agent to receive snapshots from tests and upload them to the Percy project.

Try Visual Testing using Selenium for Free

Here is the entire code for running visual tests using Selenium:

// snapshot.js
const PercyScript = require('@percy/script');

// A script to navigate our app and take snapshots with Percy.
PercyScript.run(async (page, percySnapshotExample) => {
await page.goto('https://www.google.com');
await percySnapshotExample('Google homepage');
await page.type('.new-todo', 'A necessary task');
await page.keyboard.press('Enter');
await percySnapshotExample(' tasks with a new todo', { widths: [768, 992, 1200] });
});

For example, if using Maven, the relevant command would be:

./node_modules/.bin/percy exec —- mvn test

To run the project, use the below command
export PERCY_TOKEN=your_token_here  {Please place the token that you have generated}

npx percy exec -- node snapshot.js

Now, go to the project dashboard and click on the project previously created.
It will display the builds as shown below:

Visual Testing with Selenium - Dashboard

Click on a build to check the screenshots.

Final step on Selenium Visual Testing

After checking, approve the build if all the snapshots are perfect. It is also possible to set the width and height of a screenshot and as well as the browser to be used for testing.

As demonstrated by this example, Percy by BrowserStack is an extremely effective tool for automating visual tests. It captures screenshots, compares them against the baseline images, and highlights visual changes. With increased visual coverage, teams can deploy code changes with confidence with every commit.

With Percy, testers can increase visual coverage across the entire UI and eliminate the risk of shipping visual bugs. They can avoid false positives and get quick, deterministic results with reliable regression testing. They can release software faster with DOM snapshotting and advanced parallelization capabilities designed to execute complex test suites at scale.

Percy’s SDKs enable users to easily install them and add snapshots. Percy also integrates with CI/CD pipelines and source code management systems to add visual tests to each code commit. After tests are initiated, Percy grabs screenshots, identifies visual changes, and informs the testing team of all changes. Then, testers can easily review visual diffs to decide if the changes are legitimate or require fixing.

Try Percy for Free

Visual regression testing, in particular checks, to ensure that style issues don’t pop up, when changes are being implemented in software. The application should continue to look as good as it was and should function perfectly.

By incorporating visual testing into the testing process, testers will be able to deliver visually perfect applications quickly and consistently. It also helps them create websites that maintain visual consistency across the entire UI by offering comprehensive visual reviews and accurate results. Looks do matter, especially when users have thousands of other websites to choose from.

Make your site look good and work well, and you will keep your visitors happy.

Tags
Selenium Selenium Webdriver Visual Testing

Featured Articles

5 Core Practices for Efficient Visual Testing

Why is Visual Testing Essential for Enterprises?

Cross Browser Testing vs Responsive Design Testing – what should I do?

BrowserStack Logo Deliver pixel-perfect UI with Visual Testing Run a Free Test Now