Scriptworks Logo
20th December 2021

What is Selenium? How to locally test Selenium - Guide for 2022

selenium

Selenium is a free (open-source) test automation framework that can test web applications on a variety of browsers and operating systems. Selenium scripts can be written in various computer languages, including Java, C#, Python, and more. The final result is the entire test script carried out in your chosen language. Selenium testing is used to describe testing done with the Selenium tool.

The Selenium testing tool is frequently used to automate the testing of web browsers. There are many browsers that selenium can test for, including Chrome, Firefox, Safari, and Internet Explorer.

It's easy to use Selenium WebDriver to automate browser testing on these browsers.

All web applications, regardless of browser, are best tested with a selenium testing tool and a Selenium tool suite. For all tests, it provides excellent results because of its role in automation testing.

Web browser automation is the primary use of the Selenium software package. UI testing may also be done with this tool, using Selenium UI.

Selenium testing tool is frequently used to perform regression testing. The selenium testing tool enables developers to receive instant feedback by quickly and efficiently identifying errors. An endless number of test cases can be executed with this tool.

The Selenium automated testing framework can accommodate agile and extreme development techniques. Manual testing often misses flaws that Selenium automation can detect.

With the use of SQL commands, the Selenium database testing tool may be used to do database testing.

Web application testing and cross-browser testing in selenium are the most popular services.

What is Selenium and why is it used?

Selenium is used to automate web testing browsers across multiple platforms. Chrome, Mozilla, Firefox, and Safari are all supported by Selenium WebDriver, and you can easily automate browser testing across these browsers.

You can observe automated testing in action on your computer screen at any time. However, the question we'll be addressing in this article still stands as there are various automation testing tools out there to choose from.

Frameworks and Languages

When deciding on a tool, the first question that comes to mind is, "Does my tool support the language that I know?"

However, Selenium is a different story as it supports different programming languages for software testing automation.

Thanks to Selenium, if you want to develop your scripts in any computer language, you can do it with no problem. This means that learning only Selenium-specific languages is unnecessary. Dedicated test automation frameworks for building Selenium test scripts are available for every Selenium-supported language. You don't have to worry about language and framework support when using the Selenium automation testing tool because Selenium does that for you!

Open-source

Selenium's open-source availability is just one of the numerous advantages of selenium software. Since it is open-source, Selenium is a public automation framework that requires no upfront costs to use, making it accessible to all users. As a result, you can save money here and utilize it to help others.

The Selenium community is constantly automating web browser capabilities and functionalities. In addition, the open-source nature of Selenium allows you to customize the code and expand the provided methods and classes. The ease with which a test script can be generated for validating functionality has made Selenium the most trusted web automation technology.

Web browser compatibility

"One Selenium script for all browsers" is the goal of the Selenium community every day. Selenium is compatible with all of StatCounter's top web browsers, such as Chrome, Firefox, Safari, Internet Explorer, Opera, and Edge. A single script can be written for all browser platforms.

Cross-platform testing framework

Your test automation tool must be able to run on a variety of different operating systems. As a result, Selenium can run tests on any operating system, including Windows, Linux, Mac OS X, and UNIX.

Selenium suite can be created on any platform, such as Windows, and then run on another platform, such as Mac or Linux. This makes it easier for software developers and testers to design automation test scripts without worrying about the platform on which they will be running.

Ease Of Implementation

Using the Selenium automation framework is a breeze. Selenium's user-friendly UI makes it easy to generate test scripts. In addition, you can monitor the tests while they are being carried out. Selenium test results can be analyzed in great detail, and you can take action based on the results.

Finally, you'll never feel alone. Selenium's vast network is always ready to assist you in the event of an emergency. In the community, you can ask questions and brainstorm ideas.

Integrations and reusability

As previously stated, the automated Selenium suite can be reused and tested on many browsers and operating systems. But if Selenium is not an all-encompassing web-based automation testing tool, this is a problem. Third-party frameworks and extensions are needed to expand the scope of testing.

For instance, Selenium must be integrated with TestNG and JUnit to manage test cases and generate reports. To achieve continuous testing, you'll need to combine it with CI/CD systems like Jenkins, Maven, and Docker. In addition, for image-based testing, you'll need to use tools like Sikuli and cloud-grids like LambdaTest to accomplish cross-browser testing. Selenium may be used with a wide range of management solutions.

Flexibility

In the testing lifecycle, test management is critical. Using Selenium capabilities such as regrouping and refactoring test cases becomes easier and more efficient. There are many benefits to this for developers and testers, including reduced duplication of effort and improved maintainability of the code. With these features, Selenium has an advantage over other automated tests solutions because it is more flexible and user-friendly.

Testing in parallel allows for a faster time to market

It's all about saving time and effort with automated testing. Using Selenium Grid, we can run numerous tests simultaneously, lowering the time it takes to complete a test. For cross-browser testing with Selenium, you can save time by employing cloud-grid technology, which allows you to test on hundreds of browsers simultaneously.

Less Hardware Usage

It's worth noting that Selenium is less hardware-intensive than other vendor-focused automation tools like QTP, UFT, and SilkTest when compared.

Learning and Using Selenium is progressive

Let's start with the fact that learning Selenium on your own is really challenging. You'll have to spend time and effort on this. In addition, if you have no IT experience, the task is even tougher.

After that, there are a plethora of resources (blogs, books, online courses) for beginners to learn about Selenium and Java. For novices, some of them are decent and adequate As a result, your next task is to pick out the best of the bunch.

The level of your knowledge changes as you progress from beginner to intermediate level of learning. Although there are several excellent resources for testers with intermediate knowledge of Selenium and Java, there are still some challenges.

Constantly updated

We all know that active communities don't like to remain static, so the Selenium community continually releases new and improved versions of the software. Because these changes are available and easy to grasp, they don't require any special training to use the community. As a result, Selenium is more cost-effective and resourceful than other tools.

Introduction to Selenium Testing

Selenium is a web application testing framework. To write functional tests, Selenium provides a playback tool that doesn't require you to learn programming languages (Selenium IDE).

C#, Groovy, Java, Perl, PHP, Ruby, and Scala are some of the major programming languages that can develop tests using the Selene test domain-specific language (Selenese).

Selenium is an accessible, open-source test automation technology that has become a vital part of the software testing process. Selenium WebDriver, Selenium RC, Selenium IDE, and Selenium Grid are just a few of the numerous tools that make up this testing solution.

Web applications are widely automated using Selenium, a lightweight and developer-friendly testing tool.

Webdriver automated testing may be used on any operating system, such as Windows, Linux, or OS X. It was first developed by Jason Huggins in 2004 and has since been ported to other platforms.

Testers use Selenium to perform cross-browser testing, which may also test web applications. The selenium automation testing tool is made up of many different components.

How does selenium testing work?

Selenium's design will help us understand how it works with different languages and browsers to produce the same output, i.e. test case execution, regardless of which browser is being used.

The above picture depicts an idea about the working of the selenium web driver. Below are the different modules that combine to execute the Automated Test Scripts.

Selenium Libraries

Selenium Client Libraries/language bindings have been built by developers to support different programming languages, for example, if we are using the browser drivers in java, it will use java bindings.

Data Communication

To communicate between server and client (browser), the selenium web driver uses JSON. JSON Wire Protocol is a REST API that transfers the information between HTTP servers. Each Browser Driver has its own HTTP server.

Custom Clients (Headless Browser)

As an aide to browsers, Browser Drivers are able to communicate with browsers without revealing the internal workings of the browser's capabilities. Browser Drivers take commands and execute them on the corresponding browser, returning an HTTP Response in the process. A secure connection requires a unique driver for each browser that is being used. It is faster than classic Selenium RC since all of these browser drivers work directly on top of the operating system.

Now since we have gone through what goes inside the selenium, let’s have a look at the typical case to case execution of steps when we execute a script in selenium −

  • Creates an HTTP Request for each selenium command and sends it on to the browser driver.
  • Browser Driver then sends an HTTP request to the server.
  • In this case, the processes are performed on the HTTP server.
  • Automation scripts are able to read the execution status from the HTTP server, which is subsequently passed to the script.

This was, in short order, the workings and architecture of selenium in general.

Does Selenium support integration testing?

Yes, When it comes to performing integration testing, Selenium is an excellent choice. All kinds of tests can be run using Selenium and the TestNG framework: unit, functional tests, end-to-end (integration), and so on. Selenium also supports Data Driven Testing (DDT) on the TestNG website.

The Robot Framework can be utilized for acceptance testing, acceptance test-driven development (ATDD), or the Keyword Driven Testing methodology.

What type of testing does Selenium support?

  • Acceptance testing
  • Functional testing
  • Performance testing
  • Load testing
  • Stress testing
  • Regression testing
  • Test-driven development (TDDBehavior-driven development (BDD)

How to locally test Selenium

Selenium tests can be used to execute a sequence of web browser interactions. It is possible to simulate how a user would interact with a website's components by running tests that look for text, buttons, and forms. This part will explain how to run tests on Selenium locally for front-end web testing on the local browser.

Selenium for JS

Allows Selenium to be used as a Node test runner by using the selenium-webdriver NPM module

Mocha and chai assertions, a common JS testing framework, are easy to utilize with the selenium driver.

React testing

The selenium tests in this post were written in ES6 and used to test a React application from beginning to end. After establishing a new component or changing an existing component, React developers could quickly write a new user interaction test.

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai. use(chaiAsPromised);
const expect = chai.expect;

import webdriver from 'selenium-webdriver';
import test from 'selenium-webdriver/testing';

Launch of a Local Browser

Selenium will observe the driver launch a new browser instance on the local machine when it's run locally to the user. That launch is made possible by NPM modules such as chrome driver and geckodriver. To operate a browser, you must have a browser compatible with your operating system. Using Internet Explorer on a Mac, for example, is impossible.

Browser Capabilities

The selenium webdriver receives a list of capabilities, including the platform, browser, and versioning of the browser that the webdriver will start when launched. We'll create a local instance of the chosen web browser on the user's browser for testing purposes.

let capabilities = {
  "Chrome: El Capitan": {
    'browserName': 'chrome',
    'platform': 'OS X 10.11',
    'version': '54.0',
  },
  "Firefox: El Capitan": {
    'browserName': 'firefox',
    'platform': 'OS X 10.11',
    'version': '50.0',
  },
};

Build the Webdriver and Launch the Browser

Tell the webdriver to create a browser instance in mochas before all hook. Because selenium can test against development as it happens in real-time with this example, it's great.

test.before((done)=> {
  driver = new webdriver.Builder()
  .withCapabilities(capability)
  .build();
      
  driver.get('http://127.0.0.1:3000')
  .then(()=>done());
});
test.after((done)=>{
  driver.quit()
  .then(()=>done());
});

You may now run tests as soon as the webdriver has launched your project on a browser!

Find the Elements

It is the job of selenium to locate elements of a webpage that are visible in the browser's view. User interaction is defined first in the test below so that the user can log in. Since the project it runs against compiles its CSS into unique names, the majority of these elements may be identified by their classnames. Finding elements using additional identifying features, such as an id or a tag, is also possible with Selenium webdriver's findElement function.

	test.it('log in', (done) => {
	  let usernameInput = {name: 'user[email]'};
	  let passwordInput = {name: 'user[password]'};
	  let submitButton = {className: 'EmailLoginForm__button'};
	  let handle = {className: 'CommentForm__handle'};
	  let modalError = {className: 'EmailLoginForm__error'};
	

	  driver.findElement({className: 'TabBar__loginButton'}).click() 
	  .then(()=>driver.findElement(usernameInput).sendKeys(userLogin))
	  .then(()=>driver.findElement(passwordInput).sendKeys(userPassword))
	  .then(()=>driver.findElement(submitButton).click())
	  .then(()=>driver.findElements(modalError))
	  .then((displayedError)=>{
	    if(displayedError.length){
	      console.error('User was shown an error message when logging in');
	    }
	  })
	  .then(()=>driver.wait(until.elementLocated(handle), 5000))
	  .then(()=>expect(driver.findElement(handle)
	      .getText()).to.eventually.equal('selenium test bot'))
	  .then(()=>done())
	  .catch((err)=>done(err));
	});
view raw
login.mocha.js hosted with ❤ by GitHub

Test an Interface Feature

Selenium opens a login window, enters its information, and presses the "Submit" button. A user's logged-in status is then used to determine if the test passes or fails. The test verifies that the "handle" div on the page that appears after submission contains the expected username.

	import chai from 'chai';
	import chaiAsPromised from 'chai-as-promised';
	chai.use(chaiAsPromised);
	const expect = chai.expect;
	

	import webdriver from 'selenium-webdriver';
	import test from 'selenium-webdriver/testing';
	

	let capabilities = {
	  "Chrome: El Capitan": {
	    'browserName': 'chrome',
	    'platform': 'OS X 10.11',
	    'version': '54.0',
	  },
	  "Firefox: El Capitan": {
	    'browserName': 'firefox',
	    'platform': 'OS X 10.11',
	    'version': '50.0',
	  },
	};
	

	for (let capability in capabilities){
	  describe('Selenium login: ' + capability.browserName, function() {
	

	    test.before((done)=> {
	      driver = new webdriver.Builder()
	      .withCapabilities(capability)
	      .build();
	      
	      driver.get('http://127.0.0.1:5001')
	      .then(()=>done());
	    });
	

	    test.after((done)=>{
	      driver.quit()
	      .then(()=>done());
	    });
	

	

	    test.it('log in', (done) => {
	      let usernameInput = {name: 'user[email]'};
	      let passwordInput = {name: 'user[password]'};
	      let submitButton = {className: 'EmailLoginForm__button'};
	      let handle = {className: 'CommentForm__handle'};
	      let modalError = {className: 'EmailLoginForm__error'};
	

	      driver.findElement({className: 'TabBar__loginButton'}).click() 
	      .then(()=>driver.findElement(usernameInput).sendKeys(userLogin))
	      .then(()=>driver.findElement(passwordInput).sendKeys(userPassword))
	      .then(()=>driver.findElement(submitButton).click())
	      .then(()=>driver.findElements(modalError))
	      .then((displayedError)=>{
	        if(displayedError.length){
	          console.error('User was shown an error message when logging in');
	        }
	      })
	      .then(()=>driver.wait(until.elementLocated(handle), 5000))
	      .then(()=>expect(driver.findElement(handle)
	        .getText()).to.eventually.equal('selenium test bot'))
	      .then(()=>done())
	      .catch((err)=>done(err));
	    });
	

	  });
	}

Selenium Grid

To conduct tests on remote machines, Patrick Lightbody developed Selenium Grid, which he originally named HostedQA (as part of Selenium v1). Using Grid can run multiple test scripts on multiple machines simultaneously.

An architecture called Hub-Node is used to allow for parallel execution. There will be a Hub and some nodes in the network. Hub controls the test scripts running on multiple browsers and OS systems. Each Node has its own set of programming languages that can be used to write tests.

selenium grid - what is selenium

WebDriver and RC can both be used with Grid. It is, however, challenging to maintain a grid that includes all of the browsers and operating systems that are needed. With the help of several internet platforms, you may execute your selenium automation scripts on an online Selenium Grid that you can access at any time. A good example is LambdaTest, which is free. If you want to automate cross-browser testing properly, then the selenium tool is for you.

Selenium Webdriver

WebDriver extends and improves on Selenium Remote Control, commonly referred to as "Selenium 2.0." WebDriver does what it says it will. Selenium IDE runs web browsers at a higher level.

Testers can use WebDriver to take control of the browser from an operating system level. In more elaborate automation arrangements, this can lead to significantly greater efficiency. Because of this, it is possible to test with headless browsers.

More advanced, complex, and scalable automation is better served by WebDriver.

WebDriver is W3C-compliant as of today, and even more so in the next Selenium 4 version. In its substitute, the JSON Wire Protocol, which was in use previously, has been phased out.

image-blog-w3c-protocol

:A variety of languages can be used to write test scripts using Selenium WebDriver technology.

  • Java
  • C#
  • Python
  • Ruby
  • JavaScript
  • PHP

Seven different object locators are supported by the Selenium framework for interacting with web application properties. When creating test automation, this is essential.

In addition to clicking, swiping, and entering text, the following locators are available:

  • By CSS ID: find_element_by_id
  • By CSSclass name: find_element_by_class_name
  • By name attribute: find_element_by_name
  • By DOM structure or XPath: find_element_by_xpath
  • By link text: find_element_by_link_text
  • By partial link text: find_element_by_partial_link_text
  • By HTML tag name: find_element_by_tag_name

Selenium automation testing

 Although manual testing is a critical element of the application development process, it suffers from numerous drawbacks, including monotony and repetition. An engineer at Thoughtworks named Jason Huggins came up with automating the testing process to get around these problems. Using JavaScript, he created software called JavaScriptTestRunner that automated web application testing. In 2004, this software was renamed Selenium.

Selenium automated testing has the drawback of only being used on web applications, leaving desktop and mobile apps in the dust. Tools such as Appium and HP's QTP can test software and mobile applications, among others.

Selenium Automation Testing Tools

selenium-1

Selenium consists of a set of tools that facilitate the testing process. 

selenium-2

Selenium Suite Of Tools

  • Selenium RC (Now deprecated)
  • Selenium IDE
  • Selenium Grid
  • Selenium WebDriver

Selenium Remote Control (RC)

Selenium remote control (RC) is an important component in the Selenium test suite. Any programming language can be used to construct test cases that can be run against any HTTP website to automate user interface testing for web applications.

The Selenium RC system is divided into two components:

  • For the chosen programming language, client libraries.
  • A server that automatically runs and terminates browsers.

"JavaScriptTestRunner" was the original name for Selenium-Core, a javascript code that was created by Jason Huggins in 2004. The built-in JavaScript interpreter in the browser was used to interpret and execute Selenese commands via a series of JavaScript functions. After that, Selenium-Core was injected into the browser.

Let's have a look at test.js, a JavaScript code utilized by Google.com. Within the google.com domain, this software has access to pages like google.com/mail and google.com/login.

Selenium9

Fig: Selenium RC

However, the program is unable to access Yahoo.com's features. It was necessary to install local copies of Selenium-Core and a web browser to share a domain. To address this issue, Selenium RC was introduced. This policy is known as the Same Origin Policy. Web browsers are tricked into thinking that Selenium Core and the tested web application originate from the same server using the server's client-configured HTTP proxy.

It is, therefore, possible to write application tests in Java, C#, and other programming languages like Perl, PHP, Python, etc., using Selenium RC's Java-based server. The Selenium-Core JavaScript commands that the RC server receives from the user program are passed to the browser.

Selenium IDE

Everything you need to know about the Selenium IDE is covered in the next part. In 2006, Selenium IDE Shinya Kasatani created the Selenium Integrated Development Environment (Selenium IDE). Selenium IDE simple interface that records user actions to generate automated test scripts. You can use it with the Firefox plugin or Chrome to create prototypes. Automated scripts were the primary goal of its development.

Firefox 55, which did not support Selenium IDE, was released in August 2017 and rendered Selenium Integrated Development Environment unusable. There is a new version of Selenium available for download from Applitools. The most recent version included some new features, such as:

  • Reusability of test scripts 
  • Debugging test scripts
  • Selenium side runner
  • Provision for control flow statements
  • Improved locator functionality
selenium-3.

Now let’s take a closer, more detailed look at Selenium IDE. 

How to install Selenium IDE: 

  1. Open your Firefox browser and begin using it.
  2. Right-click on the menu in the upper right-hand corner.
  3. Select Add-ons from the drop-down menu.
  4. Find more add-ons and type "Selenium IDE" in the search field
  5. Add to Firefox by clicking on it
selenium-4

After installation, the Selenium IDE icon is displayed in the browser's upper right corner. A welcome appears when you click on it.

Selenium4

Recording a Test

In this segment of Selenium automation testing, we'll learn how to record a test. The first stage is to conduct a new test for a new project. You should give your project a name, such as "Demo Project." Before recording, we must have a working URL. This URL is the starting point for the recording. Let's head over to Facebook's sign-in page.

Selenium6

Clicking on “Start Recording” will send you to the Facebook page and start recording the user interactions. The user is at liberty to stop recording. All user actions are recorded and converted into a script. 

Save Your Work 

To save your work, click the save icon in the IDE's upper-right corner to save your modifications. It will ask you to give it a name and a location to save it. a.side file is the only thing you'll get as a result.

Selenium7

Playback 

In-browser: There are several ways to play tests in the Selenium IDE, like clicking on a test, selecting it, and then using the Play button.

The command-line runner can be used for cross-browser playback.

Selenium8

As a tool for prototyping and syntax testing, Selenium's IDE lacks some of the more advanced features. Not a full-scale testing procedure. Restrictions include the inability to write in the standard programming language, the inability to test dynamic web applications, and the inability to import data to facilitate data-driven testing.

Article written by Duncan Brigginshaw

Leave a Reply

Your email address will not be published. Required fields are marked *

Get started now

Sign up now and have your first test running in minutes
Scriptworks logo
© Copyright 2022 | Scriptworks is part of Odin Technology Ltd, a company registered in England no. 03735083