<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harita Ravindranath on Medium]]></title>
        <description><![CDATA[Stories by Harita Ravindranath on Medium]]></description>
        <link>https://medium.com/@haritaravindranath?source=rss-334efde8368f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rsqqDWyyJcm6ZS89sw6JmQ.png</url>
            <title>Stories by Harita Ravindranath on Medium</title>
            <link>https://medium.com/@haritaravindranath?source=rss-334efde8368f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:12:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@haritaravindranath/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Comprehensive Guide To JavaScript Design Patterns]]></title>
            <link>https://haritaravindranath.medium.com/a-comprehensive-guide-to-javascript-design-patterns-e543222392f6?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e543222392f6</guid>
            <category><![CDATA[test]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 10:27:12 GMT</pubDate>
            <atom:updated>2026-10-21T09:25:53.203Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*ThApTV_cL3x5PiN2KHLJMQ.jpeg" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/comprehensive-guide-to-javascript-design-patterns/"><em>TestMu AI blog</em></a><em>.</em></p><p>Design Pattern is a widely acknowledged concept in the software engineering industry in terms of the benefits it brings to areas of code-reuse and maintainability. As a software developer, you likely stumble upon this term at one point. Unsurprisingly, without even knowing it, the chances are that you might have already implemented them somewhere in the development journey.</p><p>A <strong>design pattern</strong> is used to identify reusable solutions that can be applied to recurring problems that software developers commonly face during software design. They represent time-tested solutions and best practices adopted by object-oriented software developers over time.</p><p>This blog will be your guide to everything you need to know about popular JavaScript design patterns. The only prerequisite is that you should have basic knowledge of JavaScript and Object-Oriented Programming concepts.</p><p>Starting with the historical perspective, we will do an in-depth exploration of various common JavaScript design patterns from an object-oriented view. By the end, you will be accustomed to various JavaScript design patterns along with a basic idea of their implementation.</p><p>Let’s begin with our guide on JavaScript design patterns!</p><h3>History of Design Pattern</h3><p>Since its inception, the concept of design pattern has been around in the programming world. But it was not formalized till 1994 when one of the most influential work was published called “Design Patterns: Elements Of Reusable Object-Oriented Software” — written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides — a group that became known as the Gang of Four (or GoF).</p><p>In this book, 23 object-oriented design patterns are featured. Since then, the “pattern approach” became popular in the software engineering industry, and after that, dozens of other patterns have been discovered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*3Z7jr5Og_wUjxvsE.png" /></figure><h3>What is a Design Pattern?</h3><p>Design patterns can be considered pre-made blueprint applied to solve a particular design problem. It is not a finished piece of code that can be directly applied to your program. But rather, it is more like a template or description that can give you an idea of approaching a problem and inspiring solutions. Hence, the code for the two separate programming scenarios, implementing the same pattern can be different.</p><p>Now, if you are wondering how a pattern gets discovered, it’s simple. When the same solution gets repeated over and over, someone will eventually recognize it, put a name to it, and then describe the solution in detail. That’s how a pattern gets discovered. Definitely, they were not forged overnight.</p><p>A design pattern is often confused with algorithms.</p><h3>Structure of a Design Pattern</h3><p>As mentioned in the above section of the JavaScript design patterns tutorial, the author of a design pattern provides documentation. Even though there is no strict agreement among the pattern community regarding the documentation template structure, the following are the sections that are usually present.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrEc4J9rRwOcIob8&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrEc4J9rRwOcIob8&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a9546691f85a3455959620c994bd1a3/href">https://medium.com/media/9a9546691f85a3455959620c994bd1a3/href</a></iframe><p>Some other sections are Applicability, Collaborations, Consequences, etc.</p><p><strong><em>Check out this: A Complete End to End (E2E) Testing Tutorial: Comprehensive Guide With Examples and Best Practices </em></strong><a href="https://www.testmuai.com/learning-hub/end-to-end-testing/"><strong><em>https://www.testmuai.com/learning-hub/end-to-end-testing/</em></strong></a></p><h3>Why Patterns?</h3><p>As previously mentioned, we already use patterns every day. They help us solve recurring design problems. But is it necessary to spend time learning them? Let’s look into a few key benefits that design patterns grant us.</p><p><strong>1. Avoid reinventing the wheel:</strong></p><p>Most of the frequently faced design problems already have a well-defined solution that is associated with a pattern. Patterns are proven solutions that can speed up development.</p><p><strong>2. Codebase Maintenance:</strong></p><p>Patterns help in implementing DRY(Do not Repeat Yourself) — the concept which helps to prevent your codebase from growing large and unwieldy.</p><p><strong>3. Easily reused:</strong></p><p>Reusing patterns assists in preventing minor subtle issues that can cause major problems in the application development process. This also improves code readability for coders and architects familiar with the patterns.</p><p><strong>4. Enables efficient communication:</strong></p><p>Patterns add to a developer’s vocabulary. This allows developers to communicate using well-known, well-understood names for software interactions, making communication faster.</p><p><strong>5. Improve your object-oriented skills:</strong></p><p>Now even if you never encounter any of these problems, learning patterns can give you insights into various approaches to solving problems using object-oriented principles.</p><h3>Criticism of Patterns</h3><p>Over time design patterns have also received a fair share of criticism. Let’s peek into the popular arguments against patterns.</p><p><strong>1. Increases Complexity:</strong></p><p>Inappropriate use of patterns creates undesired complexity. This is a problem suffered by many novices, who try to apply the pattern wherever they can think of, even in situations where simpler code would do just fine.</p><p><strong>2. Reduced Relevance:</strong></p><p>In “<em>Design Patterns in Dynamic Languages</em>,” Peter Norvig points out that over half of the design patterns in the 1994 book (written by GoF) are workarounds for missing language features. In many cases, patterns just become kludges that gave the programming language the much-needed super-abilities it lacked then.</p><p>As the language features, frameworks, and libraries evolved, there is no reason to use a few patterns anymore.</p><p><strong>3. Lazy Design:</strong></p><p>As suggested by Paul Graham in “Revenge of the Nerds” (2002), patterns are a form of lazy design, when the developer is not focused on the problem requirement at hand. Instead of creating a new and appropriate design for the problem, they might just reuse the existing design patterns because they think they should.</p><p>So far, we have seen what design patterns are and also discussed their advantages and disadvantages. Now it’s time for in-depth exploration of various types of JS design patterns available.</p><p><strong>Note:</strong> In the upcoming sessions, we will explore object-oriented JavaScript implementations of both classical and modern design patterns. It is to be noted that a few of the classic design patterns mentioned in the GoF book have reduced relevance over time. Hence they will be omitted, and modern patterns from sources like Addy Osmani’s Learn JavaScript Design Patterns will be included.</p><p><strong><em>Test your web and mobile apps on Android Emulators online. Ensure your apps are compatible across latest and legacy Android operating systems, devices, and browsers. </em></strong><a href="https://www.testmuai.com/android-emulator-online/"><strong><em>https://www.testmuai.com/android-emulator-online/</em></strong></a></p><h3>JavaScript Design Patterns</h3><p>JavaScript is one of the most in-demand programming languages for web development today. As we will be concentrating on JavaScript design patterns in this article, let’s just have a quick recap of essential JavaScript features that will aid in smoother understanding.</p><p><strong>a) Flexible with programming styles</strong><br>JavaScript has support for procedural, object-oriented, and functional programming styles.</p><p><strong>b) Supports First-class Functions</strong><br>This means functions can be passed as arguments to other functions just like a variable.</p><p><strong>c) Prototype-based Inheritance</strong><br>Though JavaScript supports objects, unlike other OOPs languages, JavaScript doesn’t have the concept of class or class-based inheritance in its basic form. Instead, it uses something called prototype-based or instance-based inheritance.</p><p><strong>Note:</strong> In ES6, even though the keyword “class” is introduced, it still utilizes prototype-based inheritance in the hood.</p><p>To know more about defining “class” using JavaScript, do check out this useful post by Stoyan Stefanov on three ways to define a JavaScript class.</p><h3>Categories of Design Pattern</h3><p>Based on intent, the JavaScript design patterns can be categorized into 3 major groups:</p><p><strong>a) Creational Design Pattern</strong></p><p>These patterns focus on handling object creation mechanisms. A basic object creation approach in a program can lead to an added complexity. Creational JS design patterns aim to solve this problem by controlling the creation process.</p><p>Few patterns that fall under this category are — Constructor, Factory, Prototype, Singleton, etc.</p><p><strong>b) Structural Design Patterns</strong></p><p>These patterns are concerned with object composition. They explain simple ways to assemble objects and classes into larger structures. They help ensure that when one part of a system changes, the entire structure of the system doesn’t need to do the same, keeping them flexible and efficient.</p><p>Few patterns that fall under this category are — Module, Decorator, Facade, Adapter, Proxy, etc.</p><p><strong>c) Behavioral Design Patterns</strong></p><p>These patterns focus on improving the communication and assignment of responsibilities between dissimilar objects in a system.</p><p>Few patterns that fall under this category are — Chain of Responsibility, Command, Observer, Iterator, Strategy, Template, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/0*AcbCOqB60g6hw0Cd.png" /></figure><p>With this understanding of the categorization, let’s examine each JavaScript design pattern.</p><p><strong><em>Check this out: Developer Tools for Safari </em></strong><a href="https://www.testmuai.com/blog/debug-websites-using-safari-developer-tools/"><strong><em>https://www.testmuai.com/blog/debug-websites-using-safari-developer-tools/</em></strong></a></p><h4>Creational Design Patterns</h4><p><strong>1. Constructor Pattern</strong></p><p>The constructor pattern is one of the most simple, popular, and modern JavaScript design patterns. As suggested by the name, the purpose of this pattern is to aid constructor creation.</p><p>In Addy’s words-</p><blockquote>“A constructor is a special method used to initialize a newly created object once the memory has been allocated for it. In JavaScript, as almost everything is an object, we’re most often interested in object constructors.”</blockquote><p><strong>Example:</strong></p><p>In the below code, we have defined a function/class Person with attributes name and age.<br>The getDetails() method will print the name and age of the person in the format –<br>“Name is age years old!”</p><p>The syntax is given in 2 formats — (a) traditional function-based syntax and (b) EC6 class syntax.</p><p>Then, we instantiate an object for the class Person by invoking the constructor method using the new keyword and passing respective attribute values.</p><pre>//  a) Traditional &quot;function&quot; based syntax<br> <br>function Person(name,age) {<br>        this.name = name;<br>        this.age = age;<br>        this.getDetails = function () {<br>            console.log(`${this.name} is ${this.age} years old!`);<br>    <br>    }<br>}<br> <br>//  b) ES6 &quot;class&quot; syntax<br> <br>class Person {<br>    constructor(name, age) {<br>        this.name = name;<br>        this.age = age;<br>        this.getDetails = function () {<br>            console.log(`${this.name} is ${this.age} years old!`);<br>        };<br>    }<br>}<br> <br>//Creating new instance of Person<br>const personOne = new Person(&#39;John&#39;,20);<br>personOne.getDetails(); // Output - “John is 20years old!”</pre><p><strong>2. Factory Pattern</strong></p><p>The Factory pattern is another JavaScript design patterns concerned with creating objects but using some sort of generic interface. According to GoF’s book, this pattern has the following responsibility.</p><p><em>“Define an interface for creating an object, but let subclasses decide which class to instantiate.”</em></p><p>This pattern is typically used when we need to handle object groups that share similar characters yet are different through appropriate custom calls. An example would bring more clarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/0*6mFau2IYUBPli1VU.png" /></figure><p><strong>Note:</strong> Though the definition particularly mentions that an interface needs to be defined, we don’t have interfaces in JavaScript. Therefore, we are going to implement it using an alternative way.</p><p><strong>Example:</strong></p><p>Here, the <strong>shapeFactory</strong> constructor is responsible for creating new objects of the constructors’ Rectangle, Square, and Circle. The <strong>createShape()</strong> inside <strong>shapeFactory</strong> takes in parameters, depending on which it delegates the responsibility of object instantiation to the respective class.</p><pre>//Factory method for creating new shape instances<br>function shapeFactory(){<br>    this.createShape = function (shapeType) {<br> <br>        var shape;<br>        switch(shapeType){<br>            case &quot;rectangle&quot;:<br>                shape = new Rectangle();<br>                break;<br>            case &quot;square&quot;:<br>                shape = new Square();<br>                break;<br>            case &quot;circle&quot;:<br>                shape = new Circle();<br>                break;    <br>            default:<br>                shape = new Rectangle();<br>                break;<br>        }<br>        return shape;<br>    }<br>}<br> <br>// Constructor for defining new Rectangle<br>var Rectangle = function () {<br>    this.draw = function () {<br>        console.log(&#39;This is a Rectangle&#39;);<br>    }<br>};<br> <br>// Constructor for defining new Square<br>var Square = function () {<br>    this.draw = function () {<br>        console.log(&#39;This is a Square&#39;);<br>    }<br>};<br> <br>// Constructor for defining new Circle<br>var Circle= function () {<br>    this.draw = function () {<br>        console.log(&#39;This is a Circle);<br>    }<br>};<br> <br>var factory = new shapeFactory();<br>//Creating instance of factory that makes rectangle,square,circle respectively<br>var rectangle = factory.createShape(&#39;rectangle&#39;);<br>var square = factory.createShape(&#39;square&#39;);<br>var circle= factory.createShape(&#39;circle&#39;);<br> <br>rectangle.draw();<br>square.draw();<br>circle.draw();<br> <br>/*<br>  OUTPUT<br>  <br>  This is a Rectangle<br>  This is a Square<br>  This is a Circle<br> <br>*/</pre><p><strong>3. Prototype Pattern</strong></p><p>An object that supports cloning is called a <strong>prototype</strong>. Using the prototype pattern, we can instantiate new objects based on a template of an existing object through cloning.</p><p>As the prototype pattern is based on prototypal inheritance, we can utilize the native prototypical strengths of JavaScript. In the previous JavaScript design patterns, we were trying to imitate features of other languages in JavaScript, which is not the case here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*_q3OB99GGdsOIKTE.png" /></figure><p><strong>Example:</strong></p><p>Here we have a prototype class car, which is cloned to create a new object myCar using Object.create feature defined by ES5 standard.</p><pre>// Prototype Class<br>const car = {<br>    noOfWheels: 4,<br>    start() {<br>      return &#39;started&#39;;<br>    },<br>    stop() {<br>      return &#39;stopped&#39;;<br>    },<br>  };<br> <br> <br>//using Object.create to create clones - as recommended by ES5 standard<br>  const myCar = Object.create(car, { owner: { value: &#39;John&#39; } });<br>  <br>  console.log(myCar.__proto__ === car); // true</pre><p><strong>4. Singleton Pattern</strong></p><p>The singleton pattern is a creational JavaScript design patterns that restricts the instantiation of a class to a single object. It creates a new instance of the class if one doesn’t exist and if existing already, it simply returns a reference to it. It is also known as the Strict Pattern.</p><p>A singleton pattern solves two problems at the same time, violating the Single Responsibility Principle.</p><ul><li>Guarantees that there is only a single instance of a class.</li><li>Provide a global access point to this instance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/0*3TqlKdTVLblKjX2A.png" /></figure><p>A practical example would be a single database object shared by different parts of the program. There is no need to create a new instance of a database when one is already existing.</p><p>One drawback of the pattern is the difficulty associated with testing. There are hidden dependencies objects, which are difficult to single out to test.</p><p><strong>Example:</strong></p><pre>//Singleton class<br>var Singleton = (function () {<br>    var instance;<br> <br>    function createDBInstance() {<br>        var object = new Object(&quot;I am the DataBase instance&quot;);<br>        return object;<br>    }<br> <br>    return {<br>        getDBInstance: function () {<br>            if (!instance) {<br>                instance = createDBInstance();<br>            }<br>            return instance;<br>        }<br>    };<br>})();<br> <br>function run() {<br> <br>    var instance1 = Singleton.getDBInstance();<br>    var instance2 = Singleton.getDBInstance();<br> <br>    console.log(&quot;Same instance? &quot; + (instance1 === instance2));  <br>}<br> <br>run(); // OUTPUT = &quot;Same instance? true&quot;</pre><h4>Structural Design Patterns</h4><p><strong>1. Adapter Pattern</strong></p><p>The adapter is a structural JavaScript design patterns that allows objects or classes with incompatible interfaces to collaborate. It matches interfaces of different classes or objects; therefore, they can work together despite incompatible interfaces. It is also referred to as the Wrapper pattern.</p><p>A real-world analogy would be trying to connect a projector to a laptop. The projector might have a VGA plug, and the laptop might have an HDMI plug. So we require an adapter that can make these two unrelated interfaces compatible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*hHc1Ew2SeYuWK6R2.png" /></figure><p>This pattern will include a class that will be responsible for joining the incompatible interfaces/functionalities.</p><p><strong>Example:</strong></p><p>The below code shows an online flight ticket pricing calculation system. There is an old interface that performs pricing calculations in one way. There is a new, improved interface with additional features like user identification and improvised calculations.</p><p>An adapter class is introduced, which allows the client program to continue working without any API changes by matching the old interface with the new one.</p><pre>// old interface<br>function TicketPrice() {<br>    this.request = function(start, end, overweightLuggage) {<br>        // price calculation code...<br>        return &quot;$150.34&quot;;<br>    }<br>}<br> <br>// new interface<br>function NewTicketPrice() {<br>    this.login = function(credentials) { /* process credentials */ };<br>    this.setStart = function(start) { /* set start point */ };<br>    this.setDestination = function(destination) { /* set destination */ };<br>    this.calculate = function(overweightLuggage) { <br>        //price calculation code...<br>        return &quot;$120.20&quot;; <br>    };<br>}<br> <br>// adapter interface<br>function TicketAdapter(credentials) {<br>    var pricing = new NewTicketPrice();<br>  <br>    pricing.login(credentials);<br>  <br>    return {<br>        request: function(start, end, overweightLuggage) {<br>            pricing.setStart(start);<br>            pricing.setDestination(end);<br>            return pricing.calculate(overweightLuggage);<br>        }<br>    };<br>}<br> <br>var pricing = new TicketPrice();<br>var credentials = { token: &quot;30a8-6ee1&quot; };<br>var adapter = new TicketAdapter(credentials);<br> <br>// original ticket pricing and interface<br>var price = pricing.request(&quot;Bern&quot;, &quot;London&quot;, 20);<br>console.log(&quot;Old price: &quot; + price);<br> <br>// new ticket pricing with adapted interface<br>price = adapter.request(&quot;Bern&quot;, &quot;London&quot;, 20);<br>console.log(&quot;New price: &quot; + price);</pre><p><strong>2. Composite Pattern</strong></p><p>Composite is a structural JavaScript design patterns that lets you compose objects into tree structures and then work with these structures as if they were individual objects. According to GoF’s book, this pattern composes objects into tree structures to represent part-whole hierarchies. It is also known as a partitioning JS design pattern.</p><p>The perfect example of this pattern would be tree control. The nodes of the tree either contain an individual object (leaf node) or a group of objects (a subtree of nodes).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XIo5TdN52Lv4jgqD.png" /></figure><p>Modern JS frameworks like React and Vue use the composite pattern to build user interfaces. The entire view is divided into components. Each component can contain multiple components. This method is preferred because of the ease of development and scalability compared to fewer monolithic objects. The composite pattern reduces the complexity of a system by allowing you to work with small objects and build them up into larger ones.</p><p><strong>Example:</strong></p><p>A file-folder(directory) structure is explained in the below code. Here a directory can have two types of entities, a file or another directory, which can contain files or directories and so on.<br>We have two classes — File and Directory. We can add or remove files in the Directory and also getFileName, and the display will list all file names inside the directory.</p><pre>function File(name) {<br>    this.name = name;<br>}<br> <br>File.prototype.display = function () {<br>    console.log(this.name);<br>}<br> <br>function Directory(name) {<br>    this.name = name;<br>    this.files = [];<br>}<br> <br>Directory.prototype.add = function (file) {<br>    this.files.push(file);<br>}<br> <br>Directory.prototype.remove = function (file) {<br>    for (let i = 0, length = this.files.length; i &lt; length; i++) {<br>        if (this.files[i] === file) {<br>            this.files.splice(i, 1);<br>            return true;<br>        }<br>    }<br>    <br>    return false;<br>}<br> <br>Directory.prototype.getFileName = function (index) {<br>    return this.files[index].name;<br>}<br> <br>Directory.prototype.display = function() {<br>    console.log(this.name);<br>    for (let i = 0, length = this.files.length; i &lt; length; i++) {<br>        console.log(&quot;   &quot;, this.getFileName(i));<br>    }<br>}<br> <br>directoryOne = new Directory(&#39;Directory One&#39;);<br>directoryTwo = new Directory(&#39;Directory Two&#39;);<br>directoryThree = new Directory(&#39;Directory Three&#39;);<br> <br>fileOne = new File(&#39;File One&#39;);<br>fileTwo = new File(&#39;File Two&#39;);<br>fileThree = new File(&#39;File Three&#39;);<br> <br>directoryOne.add(fileOne);<br>directoryOne.add(fileTwo);<br> <br>directoryTwo.add(fileOne);<br> <br>directoryThree.add(fileOne);<br>directoryThree.add(fileTwo);<br>directoryThree.add(fileThree);<br> <br>directoryOne.display();<br>directoryTwo.display();<br>directoryThree.display();<br> <br>/*<br>Directory One<br>    File One<br>    File Two<br>Directory Two<br>    File One<br>Directory Three<br>    File One<br>    File Two<br>    File Three<br>*/</pre><p><strong>3. Module Pattern</strong></p><p>Module Pattern is another prevalent JavaScript design patterns for keeping our code clean, separated, and organized. A module is a piece of self-contained code that can be updated without affecting other components. As the concept of access modifier is not supported in JavaScript, the modules help in mimicking the behavior of private/public access hence providing encapsulation.</p><p>The typical code structure will be like this:</p><pre>(function() {<br> <br>    // declare private variables and/or functions<br> <br>    return {<br>    // declare public variables and/or functions<br>    }<br> <br>})();</pre><p><strong>Example:</strong></p><p>Here we have the flexibility of renaming like we have renamed addAnimal to add. A point to be noted is that we can’t invoke removeAnimal from an outside environment as it is dependent on the private property container.</p><pre>function AnimalContainter () {<br>    //private variables and/or functions<br>    const container = [];<br>    <br>    function addAnimal (name) {<br>    container.push(name);<br>    }<br>    <br>    function getAllAnimals() {<br>    return container;<br>    }<br>    <br>    function removeAnimal(name) {<br>    const index = container.indexOf(name);<br>    if(index &lt; 1) {<br>    throw new Error(&#39;Animal not found in container&#39;);<br>    }<br>    container.splice(index, 1)<br>    }<br>    <br>    return {<br>    public variables and/or functions<br>    add: addAnimal,<br>    get: getAllAnimals,<br>    remove: removeAnimal<br>    }<br>    }<br>    <br>    const container = AnimalContainter();<br>    container.add(&#39;Hen&#39;);<br>    container.add(&#39;Goat&#39;);<br>    container.add(&#39;Sheep&#39;);<br>    <br>    console.log(container.get()) //Array(3) [&quot;Hen&quot;, &quot;Goat&quot;, &quot;Sheep&quot;]<br>    container.remove(&#39;Sheep&#39;)<br>    console.log(container.get()); //Array(2) [&quot;Hen&quot;, &quot;Goat&quot;]</pre><p><strong>4. Decorator Pattern</strong></p><p>Decorators are a structural JavaScript design patterns that aims to promote code reuse. This pattern allows behavior to be added to an individual object dynamically, without affecting the behavior of other objects from the same class. Decorators can also provide a flexible alternative to subclassing for extending functionality.</p><p>Since JavaScript allows us to add methods and properties to objects dynamically, implementing this JavaScript design patterns is a very straight-forward process. Do check out Addy Osmani’s post to know more about Decorators.</p><p>Example:</p><p>Let’s take a look at the simple implementation.</p><pre>// A vehicle constructor<br>function Vehicle( vehicleType ){<br> <br>    // some sane defaults<br>    this.vehicleType = vehicleType || &quot;car&quot;;<br>    this.model = &quot;default&quot;;<br>    this.license = &quot;00000-000&quot;;<br> <br>}<br> <br>// Test instance for a basic vehicle<br>var testInstance = new Vehicle( &quot;car&quot; );<br>console.log( testInstance );<br> <br>// Outputs:<br>// vehicle: car, model:default, license: 00000-000<br> <br>// Lets create a new instance of vehicle, to be decorated<br>var truck = new Vehicle( &quot;truck&quot; );<br> <br>// New functionality we&#39;re decorating vehicle with<br>truck.setModel = function( modelName ){<br>    this.model = modelName;<br>};<br> <br>truck.setColor = function( color ){<br>    this.color = color;<br>};<br> <br>// Test the value setters and value assignment works correctly<br>truck.setModel( &quot;CAT&quot; );<br>truck.setColor( &quot;blue&quot; );<br> <br>console.log( truck );<br> <br>// Outputs:<br>// vehicle:truck, model:CAT, color: blue<br> <br>// Demonstrate &quot;vehicle&quot; is still unaltered<br>var secondInstance = new Vehicle( &quot;car&quot; );<br>console.log( secondInstance );<br> <br>// Outputs:<br>// vehicle: car, model:default, license: 00000-000</pre><p><strong>5. Facade Pattern</strong></p><p>The facade JavaScript design patterns consists of a facade, which is an object that acts as a “front-face” for a much complex structural code. Developers normally use this pattern when a system is very complex or difficult to understand to provide a simpler interface to the client. This helps to create an abstraction layer between what is shown publicly and what is implemented behind the curtain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*a1v-Q9EgBCwytBnw.png" /></figure><p><strong>Example:</strong></p><p>Here Mortgage is a facade for Bank, Credit, and Background.</p><pre>var Mortgage = function(name) {<br>        this.name = name;<br>    }<br>     <br>    Mortgage.prototype = {<br>     <br>        applyFor: function(amount) {<br>            // access multiple subsystems...<br>            var result = &quot;approved&quot;;<br>            if (!new Bank().verify(this.name, amount)) {<br>                result = &quot;denied&quot;;<br>            } else if (!new Credit().get(this.name)) {<br>                result = &quot;denied&quot;;<br>            } else if (!new Background().check(this.name)) {<br>                result = &quot;denied&quot;;<br>            }<br>            return this.name + &quot; has been &quot; + result +<br>                   &quot; for a &quot; + amount + &quot; mortgage&quot;;<br>        }<br>    }<br>     <br>    var Bank = function() {<br>        this.verify = function(name, amount) {<br>            // complex logic ...<br>            return true;<br>        }<br>    }<br>     <br>    var Credit = function() {<br>        this.get = function(name) {<br>            // complex logic ...<br>            return true;<br>        }<br>    }<br>     <br>    var Background = function() {<br>        this.check = function(name) {<br>            // complex logic ...<br>            return true;<br>        }<br>    }<br>     <br>    function run() {<br>        var mortgage = new Mortgage(&quot;Joan Templeton&quot;);<br>        var result = mortgage.applyFor(&quot;$100,000&quot;);<br>     <br>        alert(result);<br>    }</pre><p><strong>6. Proxy Pattern</strong></p><p>As the name suggests, the Proxy Pattern provides a surrogate or placeholder for another object to control access, reduce cost, and reduce complexity. The proxy could interface to anything — a network connection, a large object in memory, a file, or some other resource that is expensive or impossible to duplicate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*qzSoi-P2xEpc-i1_.png" /></figure><p>Here, we will create a proxy object that ‘stands in’ for the original object. The proxy interface will be the same as that of the original object so that the client may not even be aware they are dealing with a proxy rather than the real object. In the proxy, extra functionality can be provided, for example, caching, checking some preconditions, etc.</p><p>There are three common situations in which the Proxy pattern is applicable.</p><ol><li>A <strong>virtual proxy</strong> is a placeholder for expensive to create or resource-intensive objects.</li><li>A <strong>remote proxy</strong> controls access to the remote object.</li><li>A <strong>protective proxy</strong> controls access rights to a sensitive master object. The caller’s access permissions are checked prior to forwarding the request.</li></ol><p><strong>Example:</strong></p><p>The following code will aid you in getting a gist of Proxy implementation. We have an external API FlightListAPI for accessing Flight Details databases. We will create a proxy FlightListProxy which will act as the interface through which the client can access the API.</p><pre>/*  External API*/<br>var FlightListAPI = function() {<br>//creation<br>};<br> <br>FlightListAPI.prototype = {<br>getFlight: function() {<br>    // get master list of flights<br>    console.log(&#39;Generating flight List&#39;);<br>},<br> <br>searchFlight: function(flightDetails) {<br>    // search through the flight list based on criteria<br>    console.log(&#39;Searching for flight&#39;);<br>},<br> <br>addFlight: function(flightData) {<br>    // add a new flight to the database<br>    console.log(&#39;Adding new flight to DB&#39;);<br>}<br>};<br> <br>// creating the proxy<br>var FlightListProxy = function() {<br>    // getting a reference to the original object<br>this.flightList = new FlightListAPI();<br>};<br> <br>FlightListProxy.prototype = {<br>getFlight: function() {<br>    return this.flightList.getFlight();<br>},<br> <br>searchFlight: function(flightDetails) {<br>    return this.flightList.searchFlight(flightDetails);<br>},<br> <br>addFlight: function(flightData) {<br>    return this.flightList.addFlight(flightData);<br>},<br> <br>};<br> <br>console.log(&quot;----------With Proxy----------&quot;)<br>const proxy = new FlightListProxy()<br>console.log(proxy.getFlight());<br>/*<br> <br>OUTPUT<br> <br>----------With Proxy----------<br>Generating flight List<br> <br> <br>*/</pre><p><strong><em>Test your web and mobile apps on Android Emulators online. Ensure your apps are compatible across latest and legacy Android operating systems, devices, and browsers. </em></strong><a href="https://www.testmuai.com/android-emulator-online/"><strong><em>https://www.testmuai.com/android-emulator-online/</em></strong></a></p><h4>Behavioural Design Pattern</h4><p><strong>1. Chain of Responsibility Pattern</strong></p><p>This is a behavioral JavaScript design patterns that creates a chain of receiver objects for a request. This pattern promotes loose coupling. We can avoid coupling the sender of a request to a receiver, and more than one receiver can handle the request.</p><p>The receiving objects will be linked together, and they can choose to act on the request and/or pass it to the next receiver object. It is also easy to add new receiver objects to the chain.</p><p>Event Handling in DOM is one implementation of the Chain of Responsibility pattern.</p><p>Once an event is fired, it propagates through the DOM hierarchy, calling every event handler it runs into until it finds the appropriate “event listener” and then acts on it.</p><p><strong>Example:</strong></p><p>Let us consider the scenario of an ATM. When we request an amount for withdrawal, the machine processes the request and dispends the amount as combinations of available note denominations ($100, $50, $20, $10, $5, $1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/0*iNvb96kIldFUW-15.png" /></figure><p>In this code on requesting an amount, a Request object is created. This object then invokes a series of get calls, which are chained together, each one handling a particular denomination. Finally, the user receives the amount as a note combination which satisfies the amount value.</p><pre>var Request = function(amount) {<br>    this.amount = amount;<br>    console.log(&quot;Request Amount:&quot; +this.amount);<br>}<br> <br>Request.prototype = {<br>    get: function(bill) {<br>        var count = Math.floor(this.amount / bill);<br>        this.amount -= count * bill;<br>        console.log(&quot;Dispense &quot; + count + &quot; $&quot; + bill + &quot; bills&quot;);<br>        return this;<br>    }<br>}<br> <br>function run() {<br>    var request = new Request(378); //Requesting amount<br>    request.get(100).get(50).get(20).get(10).get(5).get(1);<br>}</pre><p><strong>2. Command Pattern</strong></p><p>Command Pattern is a behavioral JavaScript design patterns that aims to encapsulate actions or operations as objects. This pattern is useful in scenarios where we want to decouple or split the objects executing the commands from objects issuing the commands. Command objects allow you to centralize the processing of these actions/operations.</p><p>The four participants involved in the command pattern are command, receiver, invoker, and client.</p><ul><li><strong>Command</strong> — A command object knows about the receiver and invokes a method of the receiver. Values for parameters of the receiver method are stored in the command.</li><li><strong>Client</strong> — The client’s responsibility is to create the command object and pass it to the invoker.</li><li><strong>Invoker</strong> — The invoker receives the command object from the client, and it’s only responsibility is to call (or invoke) a command.</li><li><strong>Receiver</strong> — Then, the receiver receives the command and looks for a method to call based on the received command.</li></ul><p><strong>Example:</strong></p><p>In our example, the calculator object contains four methods — add, subtract, divide, and multiply. Command objects define a method execute, which has the responsibility of invoking a method.</p><pre>var calculator = {<br>    add: function(x, y) {<br>        return x + y;<br>    },<br>    subtract: function(x, y) {<br>        return x - y;<br>    },<br>    divide: function(x,y){<br>        return x/y;<br>    },<br>    multiply: function (x,y){<br>        return x*y;<br>    }<br>}<br>var manager = {<br>    execute: function(name, args) {<br>        if (name in calculator) {<br>            return calculator[name].apply(calculator, [].slice.call(arguments, 1));<br>        }<br>        return false;<br>    }<br>}<br>console.log(manager.execute(&quot;add&quot;, 5, 2)); // prints 7<br>console.log(manager.execute(&quot;multiply&quot;, 2, 4)); // prints 8</pre><p><strong>3. Observer Pattern</strong></p><p>The Observer is a behavioral JavaScript design patterns that lets you define a subscription mechanism to notify multiple objects (observers) about any events that happen to the object (subject) they’re observing. This pattern is also called Pub/Sub, short for Publication/Subscription. It defines a one-to-many dependency between objects, promotes loose coupling, and facilitates good object-oriented design.</p><p>The observer pattern is the foundation of event-driven programming. We write event handler functions that will be notified when a certain event fires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vV7yKY7SWjbZ1wNa.png" /></figure><p><strong>Example:</strong></p><p>We have set up a Subject function Click and extended it using the prototype. We have created methods to subscribe and unsubscribe objects to the Observer collection, which is handled by the clickHandler function. Also, there is a fire method to propagate any changes in the Subject class object to the subscribed Observers.</p><pre>function Click() {<br>    this.observers = [];  // observers<br>}<br> <br>Click.prototype = {<br> <br>    subscribe: function(fn) {<br>        this.observers.push(fn);<br>    },<br> <br>    unsubscribe: function(fn) {<br>        this.observers = this.observers.filter(<br>            function(item) {<br>                if (item !== fn) {<br>                    return item;<br>                }<br>            }<br>        );<br>    },<br> <br>    fire: function(o, thisObj) {<br>        var scope = thisObj;<br>        this.observers.forEach(function(item) {<br>            item.call(scope, o);<br>        });<br>    }<br>}<br> <br>function run() {<br> <br>    var clickHandler = function(item) { <br>        console.log(&quot;Fired:&quot; +item);<br>    };<br> <br>    var click = new Click();<br> <br>    click.subscribe(clickHandler);<br>    click.fire(&#39;event #1&#39;);<br>    click.unsubscribe(clickHandler);<br>    click.fire(&#39;event #2&#39;);<br>    click.subscribe(clickHandler);<br>    click.fire(&#39;event #3&#39;);<br> <br>}<br> <br>/* OUTPUT:<br> <br>Fired:event #1<br>Fired:event #3<br> <br>*/</pre><p><strong>4. Iterator Pattern</strong></p><p>The Iterator Pattern lets you access and traverses through elements of an aggregate object (collection) sequentially without exposing its underlying representation. This pattern allows JavaScript developers to design looping constructs that are far more flexible and sophisticated. In ES6, Iterator and Generators are introduced, which further aids in the Iteration pattern implementation.</p><p><strong>Example:</strong></p><p>This is a simple straight-forward code for front-to-back iteration. We have defined two methods for the Iterator — hasNext() and next().</p><pre>const items = [1,&quot;hello&quot;,false,99.8];<br> <br>function Iterator(items){<br>  this.items = items;<br>  this.index = 0; // to start from beginning position of array<br>}<br> <br>Iterator.prototype = {<br>  // returns true if a next element is available<br>  hasNext: function(){<br>    return this.index &lt; this.items.length;<br>  },<br>  //returns next element<br>  next: function(){<br>    return this.items[this.index++]<br>  }<br>}<br> <br>//Instantiate object for Iterator<br>const iterator =  new Iterator(items);<br>while(iterator.hasNext()){<br>  console.log(iterator.next());<br>}<br>/*<br>OUTPUT<br> <br>1<br>hello<br>false<br>99.8<br> <br>*/</pre><p><strong>5. Template Pattern</strong></p><p>The template pattern defines the skeleton of an algorithm in operation in terms of some high-level steps. These steps are themselves implemented by additional helper methods in the same class as the template method. The objects that implement these steps retain the original structure of the algorithm but have the option to redefine or adjust certain steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*tITHHgs43TbLsmBv.png" /></figure><p><strong>Example:</strong></p><p>Here we have an abstract class datastore that offers an interface to implement the template method by defining primitive steps for an algorithm. And we have a concrete MySQL class, which implements the primitive steps defined in the abstract class.</p><pre>// implement template method<br> <br>var datastore = {<br>    process: function() {<br>        this.connect();<br>        this.select();<br>        this.disconnect();<br>        return true;<br>    }<br>};<br> <br>function inherit(proto) {<br>    var F = function() { };<br>    F.prototype = proto;<br>    return new F();<br>}<br> <br> <br>function run() {<br>    var mySql = inherit(datastore);<br> <br>    // implement template steps<br> <br>    mySql.connect = function() {<br>        console.log(&quot;MySQL: connect step&quot;);<br>    };<br> <br>    mySql.select = function() {<br>        console.log(&quot;MySQL: select step&quot;);<br>    };<br> <br>    mySql.disconnect = function() {<br>        console.log(&quot;MySQL: disconnect step&quot;);<br>    };<br> <br>    mySql.process();<br> <br>}<br> <br>run();<br>/* <br> <br>MySQL: connect step<br>MySQL: select step<br>MySQL: disconnect step<br> <br>*/</pre><p><strong>6. Strategy Pattern</strong></p><p>Strategy Patterns allows one of a family of algorithms to be selected on-the-fly at runtime. The pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable at run-time without client interference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/0*cXAyAoKZXM-KIWtj.png" /></figure><p><strong>Example:</strong></p><p>We have created a class Shipping which encapsulates all possible strategies for shipping a parcel — FedEx, UPS, and USPS. Using this pattern, we can swap the strategy during runtime and generate appropriate output.</p><pre>//Strategy1 <br>function FedEx(){<br>  this.calculate = package =&gt; {<br>    //calculations  happen here..<br>    return 2.99<br>  }<br>}<br> <br>//Strategy2<br>function UPS(){<br>  this.calculate = package =&gt; {<br>    //calculations  happen here..<br>    return 1.59<br>  }<br>}<br> <br>//Strategy3<br>function USPS(){<br>  this.calculate = package =&gt; {<br>    //calculations  happen here..<br>    return 4.5<br>  }<br>}<br> <br>// encapsulation<br>function Shipping(){<br>  this.company = &quot;&quot;;<br>  this.setStrategy = (company) =&gt; {<br>    this.company=company;<br>  }<br>  this.calculate = (package) =&gt;{<br>    return this.company.calculate(package);<br>  }<br>}<br> <br>//usage<br>const fedex = new FedEx();<br>const ups = new UPS();<br>const usps = new USPS();<br> <br>const package = { from: &#39;Alabama&#39;,to:&#39;Georgia&#39;,weight:1.5};<br> <br>const shipping = new Shipping();<br>shipping.setStrategy(fedex);<br>console.log(&quot;Fedex:&quot; +shipping.calculate(package)); // OUTPUT =&gt; &quot;Fedex:2.99&quot;</pre><p><strong><em>Check this out: Developer Tools for Safari </em></strong><a href="https://www.testmuai.com/blog/debug-websites-using-safari-developer-tools/"><strong><em>https://www.testmuai.com/blog/debug-websites-using-safari-developer-tools/</em></strong></a></p><h3>Anti-Patterns</h3><p>While it’s important to know about design patterns, it is equally important to know about Anti-Patterns. If a design pattern can be considered as a best practice, an anti-pattern represents just the opposite.</p><p>The term anti-pattern was coined in 1995 by Andrew Koenig. According to Koenig, an anti-pattern is a bad solution to a particular problem that resulted in a bad situation.</p><p>Few examples of anti-patterns in JavaScript are the following:</p><ul><li>Polluting the global namespace by defining a large number of variables in the global context</li><li>Passing strings rather than functions to either setTimeout or setInterval as this triggers the use of eval() internally.</li><li>Modifying the Object class prototype (this is a particularly bad anti-pattern)</li></ul><p>To summarize, an anti-pattern is a bad design that is worthy of documenting. Knowledge about them will help you recognize such anti-patterns in your code and hence improve code quality.</p><p><strong><em>Check out this blog, Emulator vs Simulator vs Real Device Testing: Key Differences </em></strong><a href="https://www.testmuai.com/blog/emulator-vs-simulator-vs-real-device/"><strong><em>https://www.testmuai.com/blog/emulator-vs-simulator-vs-real-device/</em></strong></a></p><h3>Applying Design Patterns and Testing</h3><p>Once a design pattern has been implemented and validated, we need to ensure that it works across multiple browser and browser versions seamlessly. TestMu AI (formerly LambdaTest) is an <a href="https://www.testmuai.com/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">AI-native software testing cloud</a> that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications. It includes 3000+ browser and OS combinations, and allows <a href="https://www.testmuai.com/feature/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">browser compatibility</a> regression testing across all major browsers and browser versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pRu2hq0ChV9QvPjl.png" /></figure><p>You can also leverage <a href="https://www.testmuai.com/lt-browser/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">LT Browser</a>, a developer friendly tool to perform a detailed analysis of the <a href="https://www.testmuai.com/responsive-test-online/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">responsive tests</a> of your design patterns across popular devices and viewports.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_CINWpJjeuUF8K3N.png" /></figure><h3>Conclusion</h3><p>Design patterns represent some of the best practices adopted by experienced object-oriented software developers. They are time-tested solutions for various software design problems. In this article, we have explored common design patterns in JavaScript. Additionally, we also briefly discussed Anti-Patterns and how we can test websites with such patterns on TestMu AI platform. Hopefully, this chapter will enable you to get accustomed to various JavaScript design patterns. To dive deeper into the concept, do checkout Learn JavaScript Design Patterns by Addy Osmani.</p><figure><a href="https://accounts.lambdatest.com/register?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=register"><img alt="" src="https://cdn-images-1.medium.com/max/930/0*AMHGVNXclcmrcMVO.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e543222392f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Download Files Using JavaScript and Selenium]]></title>
            <link>https://haritaravindranath.medium.com/how-to-download-files-using-javascript-and-selenium-b75812367f9a?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b75812367f9a</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 09:27:19 GMT</pubDate>
            <atom:updated>2026-10-21T09:27:11.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ninaje6t-oTGFqmThj1Z4w.png" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/download-files-using-javascript-selenium/"><em>TestMu AI blog</em></a><em>.</em></p><p>Downloading files is one of the most popular features utilized by Internet users worldwide. Almost all web applications provide a feature that allows users to download a file from the web page. It has many use cases, from downloading your favorite music or video files to invoices and bank statements.</p><p>If you are an automation tester fixated on <a href="https://www.testmuai.com/selenium-automation/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">Selenium automation testing</a>, the chances are that you might run into a requirement of testing a feature around downloading files. While being a powerful tool for performing <a href="https://www.testmuai.com/automated-browser-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">automated browser testing</a>, Selenium natively doesn’t support download functionality. However, we can easily use Selenium to deal with file download, and this blog explores the exact scenario!</p><p>In this <a href="https://www.testmuai.com/blog/automation-testing-with-selenium-javascript/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=learning_hub">Selenium JavaScript tutorial</a>, you will learn how to download files using JavaScript and <a href="https://www.testmuai.com/blog/selenium-webdriver-tutorial-with-examples/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=blog">Selenium WebDriver.</a></p><p>Let’s get started!</p><h3>Challenges and Solutions in downloading files with Selenium</h3><p><a href="https://www.testmuai.com/selenium/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">Selenium</a> is a popular open-source tool that is used to automate web browsers. Selenium WebDriver comes with an exhaustive list of native functions that allows automation testers to effortlessly execute a wide variety of user interactions on the web application like click, type, drag and drop, etc. But when it comes to automating a feature like downloading files, things are not quite straightforward.</p><p>One obstacle that testers face while downloading files with Selenium is that every web browser offers a different UI when downloading a file. Even though there is no easy way to control the browser’s native dialogs by JavaScript, there is a workaround for it.</p><p>The solution is to trick the browser profile. By leveraging the browser profile setting, you can download files in Selenium WebDriver without interacting with the download window pop-up.</p><p>In this blog on how to download files using JavaScript, let us learn how to write automation test code to download a file using JavaScript and Selenium.</p><figure><a href="https://accounts.lambdatest.com/register?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=register"><img alt="" src="https://cdn-images-1.medium.com/max/930/0*_kMX1PUkS564zeK8.png" /></a></figure><h3>How to download files using JavaScript and Selenium?</h3><p>We will be automating the following test scenario to download files using JavaScript and Selenium:</p><p><strong>Step 1:</strong> Go to the website File Download Demo for Automation.<br><strong>Step 2:</strong> Enter data in the textarea.<br><strong>Step 3:</strong> Click the “<strong>Generate File</strong>” button to generate the text file.<br><strong>Step 4:</strong> Click the “<strong>Download</strong>” link to download the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iYKATN7ImInWKjZJ.png" /></figure><h3>Prerequisites to download files using JavaScript</h3><p>Before getting started with coding, ensure that you have the following prerequisites installed in your system to download files using JavaScript and Selenium:</p><ul><li>Install Node.js and NPM.</li><li><a href="https://www.testmuai.com/blog/configure-cucumber-setup-in-eclipse-and-intellij/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=blog">Install Eclipse and IntelliJ </a>(or any IDE of your choice).</li></ul><h3>Installation and basic project setup</h3><p>In this section of this article on how to download files using JavaScript, I will be explaining briefly how to do a basic project setup for <a href="https://www.testmuai.com/blog/automation-testing-with-selenium-javascript/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=blog">automation testing with Selenium JavaScript</a>. Feel free to skip this section if you already have a working project.</p><p><strong>Step 1:</strong> Create a project folder in the desired location in your system. Open the folder in your IDE.</p><p><strong>Step 2:</strong> Initialize the project in this folder. Run the following command.</p><p>npm init -y</p><p><strong>Step 3:</strong> Install the project dependencies. We need to install Selenium WebDriver and browser drivers. Here, I am installing the driver for the Chrome browser.</p><p>npm install --save selenium-webdriver chromedriver</p><p>With this, the project setup is now completed, and the <strong>package.json</strong> file is generated in the root folder.</p><p><strong>Step 4:</strong> To maintain the test cases, create a new folder called <strong>tests</strong>. We will be storing our test files inside this folder.</p><p>My project folder structure now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/0*Xh7DjmBFoo4keKYo.png" /></figure><p>Accelerate JavaScript Automation with Parallel testing. <a href="https://accounts.lambdatest.com/register?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=register">Try TestMu AI Now!</a></p><h3>Writing test case to download files using JavaScript</h3><p>Now, it is time to write the code! For downloading a file using Selenium, we will be making use of the <strong>click()</strong> method. The automation steps are detailed below:</p><p><strong>Step 1:</strong> Create a test file testOne.js inside the tests folder.</p><p><strong>Step 2:</strong> Inside <strong>testOne.js</strong>, pull all the required functions from <strong>node_modules</strong>.</p><pre>const { By, Key, Builder } = require(&quot;selenium-webdriver&quot;);<br>require(&quot;chromedriver&quot;);</pre><p><strong>Step 3:</strong> Create a function example(), which will be containing your test script. Feel free to provide any function name of your choice.</p><pre>async function example() {<br> <br>}</pre><p><strong>Step 4:</strong> Inside the function, let us write our test script using Selenium and JavaScript.</p><pre>async function example() {<br>  //To wait for browser to build and launch properly<br>  let driver = await new Builder().forBrowser(&quot;chrome&quot;).build();<br> <br>  try {<br>    //To go to the test website from the browser with our code.<br>    await driver.get(&quot;<a href="http://demo.automationtesting.in/FileDownload.html">http://demo.automationtesting.in/FileDownload.html</a>&quot;);<br> <br>    //To enter data inside the text area<br>    await driver<br>      .findElement(By.id(&quot;textbox&quot;))<br>      .sendKeys(&quot;I love testing!&quot;, Key.RETURN);<br> <br>    //To click on &quot;Generate File&quot; button<br>    await driver.findElement(By.id(&quot;createTxt&quot;)).click();<br> <br>    //To click on &quot;Download&quot; link<br>    await driver.findElement(By.id(&quot;link-to-download&quot;)).click();<br> <br>    //Wait for 5s till download is completed<br>    await driver.sleep(5000);<br>  } catch (e) {<br>    console.log(&quot;Error Occured:&quot;, e.name);<br>  }<br>  //It is always a safe practice to quit the browser after execution<br>  await driver.quit();<br>}</pre><p>To locate the Web Elements, I have made use of the Chrome Developer Tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q498QSPot4cgnlhK.png" /></figure><p><strong>Step 5:</strong> Now simply add the function call. The full implementation is given below</p><pre>const { By, Key, Builder } = require(&quot;selenium-webdriver&quot;);<br>require(&quot;chromedriver&quot;);<br> <br>async function example() {<br>  //To wait for browser to build and launch properly<br>  let driver = await new Builder().forBrowser(&quot;chrome&quot;).build();<br> <br>  try {<br>    //To go to the test website from the browser with our code.<br>    await driver.get(&quot;http://demo.automationtesting.in/FileDownload.html&quot;);<br> <br>    //To enter data inside the text area<br>    await driver<br>      .findElement(By.id(&quot;textbox&quot;))<br>      .sendKeys(&quot;I love testing!&quot;, Key.RETURN);<br> <br>    //To click on &quot;Generate File&quot; button<br>    await driver.findElement(By.id(&quot;createTxt&quot;)).click();<br> <br>    //To click on &quot;Download&quot; link<br>    await driver.findElement(By.id(&quot;link-to-download&quot;)).click();<br> <br>    //Wait for 5s till download is completed<br>    await driver.sleep(5000);<br>  } catch (e) {<br>    console.log(&quot;Error Occured:&quot;, e.name);<br>  }<br>  //It is always a safe practice to quit the browser after execution<br>  await driver.quit();<br>}<br> <br>example();</pre><p><strong>Step 6:</strong> Run the code. Make sure that the IDE terminal is pointed towards the tests folder location and execute the following command in the terminal.</p><p>node testOne.js</p><p>The test starts running and an instance of Chrome browser is instantiated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w8hF6zhU9Vdr4EbW.png" /></figure><p>The test gets executed successfully and the file is downloaded to your default Downloads folder location.</p><p>Pace-up your releases and ship quality products faster. <a href="https://accounts.lambdatest.com/register?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=register">Try TestMu AI Now!</a></p><p>Do you want to learn more about the exciting world of <a href="https://www.testmuai.com/javascript-automation-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">JavaScript automation testing</a>? Deep dive into how Selenium WebDriver with JavaScript can be used for <a href="https://www.testmuai.com/automation-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">automated testing</a> of web applications with this video tutorial:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBQ-9e13kJ58%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBQ-9e13kJ58&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBQ-9e13kJ58%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/43ab1bf16ef876760086502d5fbb0283/href">https://medium.com/media/43ab1bf16ef876760086502d5fbb0283/href</a></iframe><p><strong><em>Check out this blog, Emulator vs Simulator vs Real Device Testing: Key Differences </em></strong><a href="https://www.testmuai.com/blog/emulator-vs-simulator-vs-real-device/"><strong><em>https://www.testmuai.com/blog/emulator-vs-simulator-vs-real-device/</em></strong></a></p><h3>How to download files to a specific folder using JavaScript and Selenium?</h3><p>Rather than downloading into the default Downloads folder, sometimes you might need to download the files to a specific folder location for storing and verifying all the downloads. In this section of this article on how to download files using JavaScript, let us learn how to configure the code to set the browser file Download directory for Chrome driver using Selenium and JavaScript.</p><p><strong>Step 1:</strong> Make the following two additional imports in our previous code.</p><pre>const chromeDriver = require(&quot;selenium-webdriver/chrome&quot;);<br>const webdriver = require(&quot;selenium-webdriver&quot;);</pre><p><strong>Step 2:</strong> Define Chrome options. Inside setUserPreferences, set your custom download path.</p><pre>var options = new chromeDriver.Options();<br>  options.setUserPreferences({<br>    &quot;download.default_directory&quot;: &quot;your\download\folder\path&quot;,<br>  });</pre><p>For example,</p><pre>&quot;download.default_directory&quot;: &quot;D:\\Test&quot;,</pre><p><strong>Step 3:</strong> Redefine your driver instance.</p><pre>var driver = new webdriver.Builder()<br>    .withCapabilities(webdriver.Capabilities.chrome())<br>    .forBrowser(&quot;chrome&quot;)<br>    .setChromeOptions(options)<br>    .build();</pre><p>The full implementation is as shown below.</p><pre>const { By, Key, Builder } = require(&quot;selenium-webdriver&quot;);<br>require(&quot;chromedriver&quot;);<br> <br>const chromeDriver = require(&quot;selenium-webdriver/chrome&quot;);<br>const webdriver = require(&quot;selenium-webdriver&quot;);<br> <br>async function example() {<br>  //To set chromeOptions<br>  var options = new chromeDriver.Options();<br>  options.setUserPreferences({<br>    &quot;download.default_directory&quot;: &quot;D:\\Test&quot;,<br>  });<br> <br>  //To wait for browser to build and launch properly<br>  var driver = new webdriver.Builder()<br>    .withCapabilities(webdriver.Capabilities.chrome())<br>    .forBrowser(&quot;chrome&quot;)<br>    .setChromeOptions(options)<br>    .build();<br> <br>  try {<br>    //To go to the test website from the browser with our code.<br>    await driver.get(&quot;http://demo.automationtesting.in/FileDownload.html&quot;);<br> <br>    //To enter data inside the text area<br>    await driver<br>      .findElement(By.id(&quot;textbox&quot;))<br>      .sendKeys(&quot;I love testing!&quot;, Key.RETURN);<br> <br>    //To click on &quot;Generate File&quot; button<br>    await driver.findElement(By.id(&quot;createTxt&quot;)).click();<br> <br>    //To click on &quot;Download&quot; link<br> <br>    await driver.findElement(By.id(&quot;link-to-download&quot;)).click();<br> <br>    //Wait for 5s till download is completed<br>    await driver.sleep(5000);<br>  } catch (e) {<br>    console.log(&quot;Error Occured:&quot;, e.name);<br>  }<br>  //It is always a safe practice to quit the browser after execution<br>  await driver.quit();<br>}<br> <br>example();</pre><p><strong>Step 4:</strong> Run the code.</p><p>node testTwo.js</p><p>The test gets executed successfully, and the file is downloaded to the specific path mentioned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yMFo1aZWnbaBBAwD.png" /></figure><p>If you are a JavaScript developer, this certification will certify your competence as an in-depth, hands-on JavaScript automation pro.</p><figure><a href="https://www.testmuai.com/certifications/selenium-javascript-101/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=certification"><img alt="" src="https://cdn-images-1.medium.com/max/930/0*JesdFjFM5a_0eWpn.png" /></a></figure><p>Here’s a short glimpse of the Selenium JavaScript 101 certification from TestMu AI:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDQwSRfCkhSM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDQwSRfCkhSM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDQwSRfCkhSM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/40a2be7c73cf2fbb3ed3810a94055b09/href">https://medium.com/media/40a2be7c73cf2fbb3ed3810a94055b09/href</a></iframe><p><strong><em>Check this out: Dev Tools for Safari </em></strong><a href="https://www.testmuai.com/blog/debug-websites-using-safari-developer-tools/"><strong><em>https://www.testmuai.com/blog/debug-websites-using-safari-developer-tools/</em></strong></a></p><h3>How to download files using JavaScript and cloud Selenium Grid?</h3><p>In the above demo test scenarios, we learned how to download files using JavaScript and Selenium WebDriver to our local systems and execute our tests in the Chrome browser.</p><p>However, most <a href="https://www.testmuai.com/blog/build-and-execute-selenium-projects/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=blog">Selenium testing projects</a> use <a href="https://www.testmuai.com/selenium-grid-online/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">online Selenium Grid</a> to achieve cross browser testing and better test coverage to ensure that the test is working fine in all major browser-OS-device combinations.</p><p>In this section of this article on how to download files using JavaScript, let us learn how to execute our code in the cloud-based Selenium Grid provided by TestMu AI.</p><p>TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications. TestMu AI scalable cloud infrastructure helps you perform <a href="https://www.testmuai.com/learning-hub/web-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">web testing</a> and <a href="https://www.testmuai.com/web-application-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">web application testing</a> across real desktop and mobile browsers. You can execute your JavaScript automation tests instantly on TestMu AI cloud, without worrying about building or maintaining an in-house device lab.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWZlsHlReRww%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWZlsHlReRww&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWZlsHlReRww%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/13ef891b9e1052dcb831529293365cd7/href">https://medium.com/media/13ef891b9e1052dcb831529293365cd7/href</a></iframe><p>Subscribe to the TestMu AI<a href="https://www.youtube.com/@TestMuAI"> YouTube channel</a> when you want to catch up with the latest news on <a href="https://www.testmuai.com/automated-browser-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">automated browser testing</a>, <a href="https://www.testmuai.com/automated-ui-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage">automated UI testing</a>, etc.</p><p>Follow along to learn how!</p><p><strong>Step 1:</strong> Create a free account on TestMu AI and secure your unique username and access key.</p><p><strong>Step 2:</strong> Inside the test file, define all the required variables for connecting with the Remote Grid like your unique username, access key, grid host, remote grid URL etc.</p><pre>const USERNAME = &quot;YOUR_USERNAME&quot;; //replace with your username<br>const KEY = &quot;YOUR_ACCESSKEY&quot;; //replace with your accesskey<br> <br>const GRID_HOST = &quot;hub.lambdatest.com/wd/hub&quot;;</pre><pre>const gridUrl = &quot;https://&quot; + USERNAME + &quot;:&quot; + KEY + &quot;@&quot; + GRID_HOST;</pre><p><strong>Step 3:</strong> Pass the browser capabilities. You can generate your custom desired capabilities using TestMu AI<a href="https://www.testmuai.com/capabilities-generator/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webpage"> Capabilities Generator.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A6EXlkEsT-mMtpMv.png" /></figure><pre>var capabilities = {<br>    &quot;LT:Options&quot;: {<br>      user: USERNAME,<br>      accessKey: KEY,<br>      build: &quot;JavaScript and Selenium Testing&quot;,<br>      name: &quot;Download File&quot;,<br>      platformName: &quot;Windows 11&quot;,<br>      selenium_version: &quot;4.1.0&quot;,<br>      driver_version: &quot;99.0&quot;,<br>    },<br>    browserName: &quot;Chrome&quot;,<br>    browserVersion: &quot;99.0&quot;,<br>  };</pre><p>Here, I am configuring my test to run in Chrome Browser version 99.0 with Windows 11 OS using the latest Selenium 4.</p><p><strong>Step 4:</strong> The configuration is completed. Our final code now looks like this.</p><pre>const USERNAME = &quot;YOUR_USERNAME&quot;; //replace with your username<br>const KEY = &quot;YOUR_ACCESSKEY&quot;; //replace with your accesskey<br> <br>const GRID_HOST = &quot;hub.lambdatest.com/wd/hub&quot;;<br> <br>const { By, Key, Builder } = require(&quot;selenium-webdriver&quot;);<br> <br>async function example() {<br> <br>  var capabilities = {<br>    &quot;LT:Options&quot;: {<br>      user: USERNAME,<br>      accessKey: KEY,<br>      build: &quot;JavaScript and Selenium Testing&quot;,<br>      name: &quot;Download File&quot;,<br>      platformName: &quot;Windows 11&quot;,<br>      selenium_version: &quot;4.1.0&quot;,<br>      driver_version: &quot;99.0&quot;,<br>    },<br>    browserName: &quot;Chrome&quot;,<br>    browserVersion: &quot;99.0&quot;,<br>  };<br> <br>  const gridUrl = &quot;https://&quot; + USERNAME + &quot;:&quot; + KEY + &quot;@&quot; + GRID_HOST;<br> <br>  //To wait for browser to build and launch properly<br>  let driver = await new Builder()<br>    .usingServer(gridUrl)<br>    .withCapabilities(capabilities)<br>    .build();<br> <br>  try {<br>    //To go to the test website from the browser with our code.<br>    await driver.get(&quot;http://demo.automationtesting.in/FileDownload.html&quot;);<br> <br>    //To enter data inside the text area<br>    await driver<br>      .findElement(By.id(&quot;textbox&quot;))<br>      .sendKeys(&quot;I love testing!&quot;, Key.RETURN);<br> <br>    //To click on &quot;Generate File&quot; button<br>    await driver.findElement(By.id(&quot;createTxt&quot;)).click();<br> <br>    //To click on &quot;Download&quot; link<br> <br>    await driver.findElement(By.id(&quot;link-to-download&quot;)).click();<br> <br>    //Wait for 5s till download is completed<br>    await driver.sleep(5000);<br>  } catch (e) {<br>    console.log(&quot;Error Occured:&quot;, e.name);<br>  }<br>  //It is always a safe practice to quit the browser after execution<br>  await driver.quit();<br>}<br> <br>example();</pre><p><strong>Step 5:</strong> Run the code.</p><p>node testThree.js</p><p>The test starts running. Go to the TestMu AI<a href="https://accounts.lambdatest.com/login?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=login"> Dashboard</a> to observe the live running status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qWcadnLjFltk16uX.png" /></figure><p>Our test got executed successfully. You can analyze the detailed report containing video and logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8pwD0TmDzn59NkHh.png" /></figure><p>Moreover, you can navigate to the TestMu AI<a href="https://accounts.lambdatest.com/login?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=login"> Analytics Dashboard</a> to see test performance metrics. You can see the total number of tests passed or failed from the Test Summary section. You can also see the snapshot of consistent tests from the Test Overview section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6Bv_4HnOpO8v4nq1.gif" /></figure><figure><a href="https://www.testmuai.com/webinar/bdd-pitfalls-and-how-to-avoid-them/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=webinar"><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zuFO2WD7t41uac9Q.png" /></a></figure><p><strong><em>Check this out: Developer Tools for Safari </em></strong><a href="https://www.testmuai.com/blog/debug-websites-using-safari-developer-tools/"><strong><em>https://www.testmuai.com/blog/debug-websites-using-safari-developer-tools/</em></strong></a></p><h3>Conclusion</h3><p>File Download is a common feature offered by most web applications. In this tutorial on how to download files using JavaScript and Selenium, we explored how to write an automation test case for downloading a file using JavaScript and Selenium WebDriver.</p><p>Additionally, we explored edge cases like how to download files using JavaScript to a specific folder and how to run our tests using an online Selenium Grid for better <a href="https://www.testmuai.com/blog/code-coverage-vs-test-coverage/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=sep30_sd&amp;utm_term=sd&amp;utm_content=blog">test coverage</a> and cross browser testing. I hope this tutorial turned out to be beneficial!</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b75812367f9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Your First Test With NightWatchJS]]></title>
            <link>https://haritaravindranath.medium.com/running-your-first-test-with-nightwatchjs-1b8ba0b81de7?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b8ba0b81de7</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[nightwatchjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[test]]></category>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Tue, 07 Jun 2022 17:30:01 GMT</pubDate>
            <atom:updated>2026-10-21T10:02:32.493Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*06CkuGasZ8YESXaSJSySSA.jpeg" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/nightwatch-js-tutorial-for-test-automation-beginners/"><em>TestMu AI blog</em></a><em>.</em></p><p>In the world of automation testing, Selenium continues to be the most sought after tool. With shorter development cycles and faster releases backed by Agile and DevOps, companies are keen on adopting the right automation testing strategy on par with the development and ensure a high-quality end product. Speeding up automation testing means choosing a plan that aids in handling repetitive work and optimizing tasks with minimal maintenance and effort. And herein lies the importance of implementing the right test automation framework.</p><p>Various test automation frameworks are available in the market to choose from. Nightwatch.js is one such well-favored JavaScript-based framework since its release in 2014. This blog will be your guide to everything you need to know to kickstart your journey in <a href="https://www.testmuai.com/selenium-automation-testing-with-nightwatchjs-framework/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun07_sd&amp;utm_term=sd&amp;utm_content=webpage">Nightwatch.js for Selenium automation testing.</a></p><p>Starting with a brief overview, our primary focus in this Nightwatch.js tutorial would be setting up and configuration of Nightwatch.js into your system. And by the end, you will be able to write your first test in Nightwatch.js Selenium.</p><p>Let’s get started!</p><h3>What Is Nightwatch.js?</h3><p>Nightwatch.js is an open-source automated testing framework for browser-based web applications and websites. It is written in Node.js runtime and uses the W3C WebDriver API (formerly Selenium WebDriver) for interacting with various browsers to perform commands and assertions on DOM elements.</p><h3>Why Is Nightwatch.js So Popular?</h3><p>The reason behind Nightwatch.js popularity is its out of the box features. Some of the noteworthy features that make Nightwatch.js so popular are:</p><ol><li><strong>Easy To Use </strong>— with a clean and simple syntax, code can be written swiftly and efficiently.</li><li><strong>In-Built Test Runner </strong>— comes with an inbuilt command-line test runner suite with Grunt support for executing Selenium automated tests.</li><li><strong>Page Object Model </strong>— supports CSS and XPath locators making browser automation more manageable.</li><li><strong>Flexibility </strong>— enables unit, integration as well as end-to-end testing.</li><li><strong>Selenium Server Support </strong>— it can automatically control the standalone Selenium server or various browser web drivers.</li><li><strong>Integrations </strong>— provides a single integrated solution for application testing, eliminating the dependency on third-party software.</li><li><strong>Support For Cloud Services </strong>— compatible with cloud-based testing platforms like TestMu AI.</li><li><strong>Continuous Integration </strong>— supports software like Jenkins, TeamCity, etc., assisting developers in continuously building and testing software.</li></ol><h3>Nightwatch.js Installation &amp; Local Set Up</h3><p>It is time to proceed with the installation and environment set-up for Nightwatch.js automation. We will be going step by step from the beginning. But, before installing Nightwatch.js, make sure your system is pre-equipped with the following.</p><p><strong>Prerequisites:</strong></p><p><strong>a) Java</strong></p><p>Check whether Java is already installed in your system using the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/0*lNonXrYzKC0W7hkG.png" /></figure><p>If not, install the latest JDK appropriate to your machine from <a href="https://www.java.com/en/download/help/download_options.html">here</a>.</p><p><strong>b) Node.js &amp; NPM</strong></p><p>Check whether Node.js is already installed in your system using the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/0*6OoPea-uOtLRwGZJ.png" /></figure><p>If not, install the latest LTS version from <a href="https://nodejs.org/en/">here</a>.</p><p><strong>Note:</strong> NPM will be installed along with Node.js. So no need for separate installation.<br>After installation, verify the version of Node.js and npm using these commands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/0*6G87eNpvXWPm19MV.png" /></figure><p><strong>c) Visual Studio Code</strong></p><p>Here, we are using Visual Studio Code as the IDE. You can choose any other IDE of your choice.</p><p>If not already installed, you may download VSC from <a href="https://code.visualstudio.com/download">here</a>.</p><h3>Installing Nightwatch.js &amp; Project Setup</h3><p>Now let’s proceed with Nightwatch.js installation and basic project configuration. As promised, we will go step by step.</p><p><strong>Step 1:</strong> Create a folder for your project in the desired location in your system. Open the folder in your IDE.</p><p><strong>Step 2:</strong> Now, let us initialize our project with the <strong>package.json</strong> file.</p><ul><li>Open the terminal in Visual Studio Code.</li><li>Verify that it is pointing to the project folder location.</li><li>Give the command:</li></ul><p>npm init</p><ul><li>You will be asked to fill in project details. You may fill them or leave them blank as of now.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*4vdkESFXppQw1709.png" /></figure><ul><li>You will also notice the package.json file is created in your project folder, containing all the project configuration details.</li></ul><p><strong>Tip:</strong> Save some time by using the following command in order to generate a default package.json file without any questions being asked.</p><p>npm init -y</p><p>Here y stands for “yes”.</p><ul><li>We have successfully created the package.json file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgYeMBvSihDIyyma7odNmA.png" /></figure><p><strong>Step 3:</strong> Let’s install Nightwatch.js to our project.</p><p>npm install --save-dev nightwatch</p><p>This command will add the “node_modules” folder in your directory and download Nightwatch.js to save it as devDependency in <strong>package.json</strong>.</p><p>You will also notice that the “package-lock.json” file has been created as well. This file is used to lock all the dependencies with the version number so that it will be easier to set up the code in another system.</p><p><strong>Tip:</strong> You may also install Nightwatch.js globally so that it is accessible for all the projects located anywhere within the system.</p><pre>npm install --save-dev nightwatch -g</pre><p>Here g stands for “global”.</p><p><strong>Step 4:</strong> Now let us install our browser web driver.</p><p>a) ChromeDriver</p><pre>npm install --save-dev chromedriver</pre><p>b) GeckoDriver (Firefox)</p><pre>npm install — save-dev geckodriver</pre><p>Or why not install them all in one go?</p><pre>$ npm i nightwatch geckodriver chromedriver — save-dev</pre><p><strong>Tip:</strong> Alternatively, we can combine steps 4 and 5 into a single step. Use the command:</p><pre>npm install — save-dev nightwatch chromedriver</pre><p>It is to be noted that, while the Selenium Server was required with older Nightwatch versions (v0.9 and prior), starting with version 1.0 Selenium is no longer necessary.</p><p>The setup is now completed! Let’s run some demo tests now!</p><h3>Running A Demo Test</h3><p>Do you know Nightwatch.js comes with some sample tests? Shall we try running that? That’s what this section of our Nightwatch.js tutorial is all about.</p><p>Let us begin-</p><p><strong>Step 1:</strong> Go to the folder “<strong>node_modules/nightwatch/examples/tests/</strong>”.</p><p><strong>Step 2:</strong> Under the ‘tests’ folder, you can find some sample tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/0*tm37V2-by63zim2w.png" /></figure><p><strong>Step 3:</strong> Let us run the first sample test “<strong>ecosia.js</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*hKjDsBDmgvYowmRy.png" /></figure><p>This is a simple, straightforward program which-</p><ol><li>Launches the default browser</li><li>Opens the search engine “Ecosia”</li><li>Inputs “nightwatch” in search field</li><li>Verifies the search result.</li></ol><p>Let’s go for it!</p><p><strong>Step 4:</strong> In the terminal run the command:</p><pre>./node_modules/.bin/nightwatch node_modules/nightwatch/examples/tests/ecosia.js</pre><p>Here, “./node_modules/.bin/nightwatch” represents the path of nightwatch.js executable.</p><p>“node_modules/nightwatch/examples/tests/ecosia.js” gives the path of the test file.</p><p><strong>Step 5:</strong> The code gets executed, and the test starts running. Default browser will get launched, and the test gets executed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Hcu79F37u2f2YDEu.png" /></figure><p><strong>Step 6:</strong> Observe the test run result in your terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OMOLNfcf2iRTgb-M.png" /></figure><p>Congrats! Nightwatch is now successfully configured in your system.</p><p><a href="https://www.testmuai.com/blog/nightwatch-js-tutorial-for-test-automation-beginners/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun07_sd&amp;utm_term=sd&amp;utm_content=blog">Nightwatch.js Tutorial For Test Automation Beginners — With Examples</a></p><h3>Writing Your First Nightwatch.js Automation Test Script</h3><p>In the previous section, we were able to run a demo test successfully. But we need to write our own scripts, don’t we?</p><p>Now that we have got a basic hand-on, it’s time to get our hands dirty. In this session, we will be writing and running our very first test file using Nightwatch.js automation. Let’s check out the configurations that need to be done.</p><p><strong>Configurations</strong></p><p>Our goal is to run our test files using the “<strong>npm test</strong>” command from the project’s base directory. Also, we are setting Chrome as our default browser in the example. But feel free to use the browser of your choice.</p><p>Now let’s start step by step.</p><p><strong>Step 1:</strong> Let us create two folders in our root directory — “tests” for keeping test files and “reports” where reports will get stored after each test run.</p><p>(You can provide any folder name of your choice. However, it should be properly mapped in the nightwatch.json file about which we will discuss in step 3.)</p><p><strong>Step 2:</strong> In your package.json file, replace “scripts — test” to “<strong>nightwatch</strong>”.</p><pre>“scripts”: {<br>  “test”: “nightwatch”<br>}</pre><p><strong>Step 3:</strong> In root, create a “nightwatch.json” file. Paste the following snippet.</p><pre>{<br>    &quot;src_folders&quot; : &quot;tests&quot;,<br>    &quot;output_folder&quot; : &quot;reports&quot;,<br> <br>    &quot;webdriver&quot; : {<br>        &quot;start_process&quot;: true,<br>        &quot;server_path&quot;: &quot;node_modules/chromedriver/lib/chromedriver/chromedriver.exe&quot;,<br>        &quot;host&quot;: &quot;localhost&quot;,<br>        &quot;port&quot;: 4444<br>      },<br>      &quot;test_settings&quot; : {<br>        &quot;default&quot; : {<br>            &quot;desiredCapabilities&quot; : {<br>                &quot;browserName&quot; : &quot;chrome&quot;            <br>              }           <br>          }<br>      }<br>}</pre><p>The “<em>nightwatch.json</em>” is the configuration file which the nightwatch test runner binary expects.</p><p>Let’s have a close look into the above code structure of “<em>nightwatch.json</em>”.</p><ul><li><strong>src_folders:</strong> indicates the location that contains the test suites. You can also give an array of folders. If not specified, we should pass the test location inline as the second argument to the <a href="https://nightwatchjs.org/guide/running-tests/#nightwatch-runner">test runner</a>, as we did in our demo test.</li><li><strong>output_folder:</strong> indicates the location where test reports get saved, i.e., JUnit report files, XML reports, test logs, selenium log, screenshots, video logs, network logs, etc.</li><li><strong>webdriver:</strong> an object containing WebDriver related configuration options.</li><li><strong>start_process:</strong> a boolean value that indicates that, once we start our test, the nightwatch will automatically start/stop the webdriver instance in the background as a child process.</li><li><strong>server_path:</strong> Here, we are giving the path of the chrome driver executable. Only useful if start_process is enabled.</li><li><strong>host:</strong> We are using localhost for running our test. Mainly needed when the WebDriver service is running on a different machine.</li><li><strong>port:</strong> The port number on which the WebDriver service will listen and/or on which Nightwatch will attempt to connect.</li><li><strong>test-settings:</strong> Defines the browser we want to use.</li></ul><p>You may also create “<strong>nightwatch.conf.js</strong>” for configuration. If both these files are present in the project, the nightwatch.conf.js file will be given more precedence over nightwatch.json.</p><p><strong>Step 4:</strong> Configurations are done. Now let us write our first test.</p><h3>Writing Nightwatch.js Automation Tests?</h3><p>We have already created a “<strong>tests</strong>” folder. Now we will be creating test files inside this folder. Each file inside it will be loaded as a test suite by the Nightwatch test runner. Let’s start!</p><p><strong>Step 1:</strong> Create a test file and name it as — <strong>testfile1.js</strong></p><p><strong>Step 2:</strong> Let’s create the test structure.</p><pre>module.exports = {<br> <br>}</pre><p><strong>Step 3:</strong> Inside each file, the test runner will look for different keys that are exported. The key is basically the test case name. Each key is mapped to a function in which the browser instance will be passed as an argument.</p><pre>module.exports = {<br>&quot;Get URL and title&quot; : function(browser) {<br>}</pre><p><strong>Step 4:</strong> Inside this function, we write our test code. Let’s see the snippet below:</p><pre>module.exports = {<br>    &quot;Get URL and title&quot; : function(browser) {<br>     browser<br>     .url(https://medium.com/&quot;%3Ca%20href=%22/service/http://www.google.com/%22%3Ehttp://www.google.com%3C/a%3E&quot;)<br>     .assert.urlContains(&quot;google&quot;)<br>     .assert.title(&quot;Google&quot;)<br>     .pause(3000);<br>       }<br>}</pre><p>Here we are trying to launch Google and verify that the title and URL of the output page match the expected result. Simple and straightforward.</p><p>Let’s understand the code now.</p><ul><li><strong>url() </strong>— navigate to a specific URL.</li><li><strong>urlContains() </strong>— checks if the current URL contains the given value.</li><li><strong>title() </strong>— checks if the page title equals the given value.</li><li><strong>pause() </strong>— suspends the test for the given time in milliseconds.</li><li><strong>assert </strong>— when an assertion fails, the test ends, skipping all other assertions.</li></ul><p><strong>Step 5:</strong> Now it’s time to run the code. Go to the terminal. Verify you are in the project base directory. Give the following command:</p><pre>npm test</pre><p>The test will start running, and the browser will be launched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q0xSboQnUFkfcaLm.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*ahX4J1OXClzXk7Iy.png" /></figure><p>All assertions are passed. Congrats, you have successfully written your first test code!</p><p><strong>Step 6:</strong> Check out the reports generated in your “reports” folder.</p><p>In this sample test case, we have explored only a few commands. Feel free to explore more by visiting the <a href="https://nightwatchjs.org/api/">official API documentation</a>.</p><h3>Parallel Testing Using Nightwatch.js</h3><p>We can enable parallel testing in Nightwatch.js using a quick and simple configuration in our “nightwatch.json” file.</p><pre>&quot;test_workers&quot;: {<br>        &quot;enabled&quot;: true,<br>        &quot;workers&quot;: &quot;auto&quot;<br>      },</pre><p>By enabling “test_workers” to be true, we are enabling parallel testing. Let’s look into the steps now:</p><p><strong>Step 1:</strong> Add the above code in your “nightwatch.json” file.</p><p><strong>Step 2:</strong> Create an additional test file in the “tests” folder for running in parallel with the first test file.</p><p><strong>Step 3:</strong> In the Terminal, give the command:</p><pre>npm test</pre><p><strong>Step 4:</strong> Two browser windows get launched, executing the test files in parallel.</p><p><strong>Step 5:</strong> After execution, observe the reports generated.</p><p><strong><em>Do you know </em></strong>CSS inline-block<strong><em> display a single element as a block while flowing text around it.</em></strong></p><h3>Cross Browser Testing &amp; Test Coverage Across Devices</h3><p>We came to a detailed understanding of Nightwatch.js setup and test execution in our local machine through the previous sections of this Nightwatch.js tutorial. We have also created our first test file, did parallel testing, and generated reports.</p><p>But to stay ahead in a highly competitive market, it is our duty as testers to ensure the quality of the application in all scenarios, i.e, the app should behave as expected across all platforms, browsers, and devices without crashing. This is where the terms test coverage and cross browser testing comes into the picture.</p><p>To leverage the test coverage, cloud-based solutions are widely adopted by companies due to various merits like:</p><ul><li>Low investment cost compared to buying the infrastructure.</li><li>Provides access to hundreds of device and platform combinations.</li><li>Extends supports to old and outdated browser versions and OS devices</li><li>No set-up or installation, or maintenance needs to be done locally.</li><li>Scalability.</li></ul><p>When it comes to distributed test execution, Selenium Grid is always a good call. It has the capability to run test cases on different versions of browsers and different operating systems simultaneously.</p><p>Hence, using a combination of Selenium Grid with the right cloud-based solution provider for cross <a href="https://www.testmuai.com/feature/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun07_sd&amp;utm_term=sd&amp;utm_content=webpage">browser compatibility testing</a> is the optimum strategy that you can deploy to assure quality. Now let us see how we can perform automated browser testing using a remote Selenium Grid provided by TestMu AI.</p><p><strong><em>Check this out- </em></strong>CSS min/max-width/height<strong><em>: Use min-width, max-width, min-height, and max-height to set a minimum or maximum width, or minimum or maximum height for an element.</em></strong></p><h3>Test Execution With Selenium Grid Cloud</h3><p>TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications. TestMu AI provides you access to 3000+ browser and OS combinations to help you gain the maximum test coverage during the automated browser testing.</p><p>You can even leverage parallel testing with Selenium automation testing, along with our open Selenium API to help you extract test reports of your Selenium script execution over TestMu AI, effortlessly.</p><p>Now, let us try and execute the above test case using the remote WebDriver for TestMu AI’s <a href="https://www.testmuai.com/selenium-automation/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun07_sd&amp;utm_term=sd&amp;utm_content=webpage">Selenium Grid cloud</a>. You can achieve this using a few simple and easy steps with few changes in your existing script for local setup. Let’s look into it step by step.</p><p><strong>Step 1:</strong> We need to pass browser and environment details to the TestMu AI Selenium Grid via the desired capabilities class. Unlike in local setup, now we have the flexibility to choose the precise settings we want.</p><p>There is a helpful tool provided by TestMu AI to generate desired capabilities based on the combination we want. Visit TestMu AI<a href="https://www.testmuai.com/capabilities-generator/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun07_sd&amp;utm_term=sd&amp;utm_content=webpage"> Desired Capabilities</a> page to generate them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iSWCsSizQKv7VKhx.png" /></figure><p>In this case, the desired capabilities class in nightwatch.json will look like this:</p><pre>&quot;desiredCapabilities&quot;: {<br>       &quot;build&quot;:&quot;Nightwatch-Selenium--Test&quot;,<br>       &quot;platform&quot; : &quot;Windows 10&quot;,<br>       &quot;browserName&quot; : &quot;Chrome&quot;,<br>       &quot;version&quot; : &quot;87.0&quot;,<br>       &quot;selenium_version&quot; : &quot;3.13.0&quot;,<br>        &quot;geoLocation&quot; : &quot;IN&quot;,<br>        &quot;chrome.driver&quot; : &quot;87.0&quot;,<br>    }</pre><p><strong>Step 2:</strong> Now you need to fetch your unique Access token and username.</p><p><strong>Step 3:</strong> Log in to TestMu AI or create your <a href="https://accounts.lambdatest.com/register?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun07_sd&amp;utm_term=sd&amp;utm_content=its_sign_up">account</a>. A unique access token will be created for you.<br>This token is used as a secret key to link your local scripts with the TestMu AI platform.</p><p>There are 3 ways to find it:</p><ol><li>If already logged in, from the Capabilities generator page, you can fetch it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/0*p7qGy2bPGHFueIH1.png" /></figure><p>2. You can also fetch the details from the <a href="https://accounts.lambdatest.com/login?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun07_sd&amp;utm_term=sd&amp;utm_content=its_sign_up">Profile section</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rWdRduThBsXf2ZPC.png" /></figure><p>3. Or from the Automation dashboard page, by clicking the key button in the top right corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*ZVPAn2YOr9o4jAdo.png" /></figure><p><strong>Step 4:</strong> Paste the following snippet in your nightwatch.conf.js file. (If not created already, you can create this file in your root)</p><p>Here we are declaring the user configuration for an access key, username, host, and port for the test.</p><pre>module.exports = (function(settings) {<br>    console.log(settings[&quot;test_settings&quot;][&quot;default&quot;][&quot;username&quot;])<br>    if (process.env.LT_USERNAME) {<br>      settings[&quot;test_settings&quot;][&quot;default&quot;][&quot;username&quot;] = process.env.LT_USERNAME;<br>    }<br>    if (process.env.LT_ACCESS_KEY) {<br>      settings[&quot;test_settings&quot;][&quot;default&quot;][&quot;access_key&quot;] = process.env.LT_ACCESS_KEY;<br>    }<br>    if (process.env.SELENIUM_HOST) {<br>      settings.selenium.host = process.env.SELENIUM_HOST;<br>    }<br>    if (process.env.SELENIUM_PORT) {<br>      settings.selenium.host = process.env.SELENIUM_PORT;<br>    }<br>    return settings;<br>  })(require(&#39;./nightwatch.json&#39;));</pre><p><strong>Step 5:</strong> Configure your nightwatch.json file. Since we are using TestMu AI, why don’t we go for cross browser testing across multiple platforms?</p><p>In this code, we are configuring for the script to run across 3 browsers — Chrome, Firefox, and Safari on 2 different platforms — Windows and macOS.</p><p>Check out the code below and let’s look into the required changes and additions to be made on your existing file:</p><pre>{<br>  &quot;src_folders&quot; : &quot;tests&quot;,<br>  &quot;output_folder&quot; : &quot;reports&quot;,<br> <br>  &quot;test_workers&quot;: {<br>    &quot;enabled&quot;: true,<br>    &quot;workers&quot;: &quot;auto&quot;<br>  },<br>  &quot;selenium&quot; : {<br>    &quot;start_process&quot; : false,<br>    &quot;server_path&quot; : &quot;&quot;,<br>    &quot;log_path&quot; : &quot;&quot;,<br>    &quot;host&quot; : &quot;hub.lambdatest.com&quot;,<br>    &quot;port&quot; : 80,<br>    &quot;cli_args&quot; : {<br>    &quot;webdriver.chrome.driver&quot; : &quot;&quot;,<br>    &quot;webdriver.ie.driver&quot; : &quot;&quot;,<br>    &quot;webdriver.firefox.profile&quot; : &quot;&quot;<br>    }<br>  },<br>  &quot;test_settings&quot; : {<br>    &quot;default&quot; : {<br>    &quot;launch_url&quot; : &quot;<a href="http://google.com/">http://google.com</a>&quot;,<br>    &quot;selenium_port&quot;  : 80,<br>    &quot;selenium_host&quot;  : &quot;<a href="https://lambdatest.com/">https://lambdatest.com</a>&quot;,<br>    &quot;silent&quot;: false,<br>    &quot;screenshots&quot; : {<br>        &quot;enabled&quot; : true,<br>        &quot;path&quot; : &quot;&quot;<br>    },<br>    &quot;username&quot; : &quot;haritagr16&quot;,<br>    &quot;access_key&quot; : &quot;123456789&quot;,<br> <br>    &quot;skip_testcases_on_fail&quot;: false,<br>    <br>    &quot;desiredCapabilities&quot;: {<br>       &quot;build&quot;:&quot;Nightwatch-Selenium--Test&quot;,<br>       &quot;platform&quot; : &quot;Windows 10&quot;,<br>       &quot;browserName&quot; : &quot;Chrome&quot;,<br>       &quot;version&quot; : &quot;87.0&quot;,<br>       &quot;selenium_version&quot; : &quot;3.13.0&quot;,<br>       &quot;visual&quot;:true,<br>        &quot;video&quot;:true,<br>        &quot;console&quot;:true,<br>        &quot;geoLocation&quot; : &quot;IN&quot;,<br>        &quot;chrome.driver&quot; : &quot;87.0&quot;,<br>        &quot;network&quot;:true<br>    }<br>    },<br>    &quot;chrome&quot;: {<br>    &quot;desiredCapabilities&quot;: {<br>        &quot;platform&quot;: &quot;Windows 10&quot;,<br>        &quot;browserName&quot;: &quot;chrome&quot;,<br>        &quot;version&quot;: &quot;87.0&quot;<br>    }<br>    },<br>    &quot;safari&quot; : {<br>    &quot;desiredCapabilities&quot;: {<br>        &quot;platform&quot;: &quot;macos 10.13&quot;,<br>        &quot;browserName&quot;: &quot;safari&quot;,<br>        &quot;version&quot;: &quot;11.0&quot;<br>    }<br>    },<br>    &quot;firefox&quot; : {<br>    &quot;desiredCapabilities&quot;: {<br>        &quot;platform&quot;: &quot;win10&quot;,<br>        &quot;browserName&quot;: &quot;firefox&quot;,<br>        &quot;version&quot;: &quot;60&quot;<br>    }<br>    },<br>    &quot;edge&quot; : {<br>    &quot;desiredCapabilities&quot;: {<br>        &quot;platform&quot;: &quot;Windows 10&quot;,<br>        &quot;browserName&quot;: &quot;MicrosoftEdge&quot;,<br>        &quot;version&quot;: &quot;17.0&quot;<br>    }<br>    <br>    }<br>  }<br>}</pre><ol><li>Pass your Access Token and User details.</li><li>Provide Desired Capabilities for all the browsers.</li><li>Set the Hostname corresponding to TestMu AI.</li><li>Optionally we have also enabled report formats like video recording, console, network logs, etc., to be true.</li></ol><p>A more detailed explanation is given below but feel free to skip to Step 6.</p><p>We have used additional parameters to configure “nightwatch.json” for cloud-based cross browser testing. They are:</p><ul><li><strong>selenium </strong>— an object containing Selenium Server related configuration options. If “<strong>selenium</strong>” is not used, “<strong>webdriver</strong>” options should be set instead (as we did in our local set up). Starting with Nightwatch 1.0, Selenium is only required when testing against a grid setup or a cloud testing service such as TestMu AI.</li><li><strong>cli_args </strong>— list of CLI args to be passed to Selenium process, basically browser drivers.</li><li><strong>test_settings:</strong></li><li><strong>silent </strong>— whether to show the extended HTTP traffic command logs from the WebDriver or Selenium server.</li><li><strong>desiredCapabilities </strong>— an object to specify browser name for instance along with other capabilities.</li><li><strong>username and access_key </strong>— Usually only needed for cloud testing Selenium services. In case the server requires credentials these values will be used to compute the Authorization header.</li></ul><p><strong>Step 6: </strong>In package.json, change the “ scripts — test” argument value.</p><p>This is important as it is here where we are specifying the browsers where we need to run our test.</p><pre>```&quot;scripts&quot;: {<br>    &quot;test&quot;: &quot;./node_modules/.bin/nightwatch -e firefox,safari,chrome tests&quot;<br>  }</pre><p><strong>Step 7:</strong> Execute the test.</p><p>npm test</p><p>The code starts running and logs can be observed in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IMNOnHpPnvcaHma8.png" /></figure><p>To observe live running status go to your Automation dashboard in TestMu AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GS4IBKAsbRKzEHH0.png" /></figure><p>We can analyze individual test run reports from Automation Logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x7rJ_kGDGpyuUjWE.png" /></figure><p>We have successfully run our test cases using an automated cross browser testing solution provided by TestMu AI through a hassle-free experience!</p><p><strong><em>Do you know </em></strong>CSS justify-content: space-evenly<strong><em> value spreads the space between items evenly. It is similar to space-around, however it gives equal room on the edges rather than half-sized space. It can be used in both CSS flexbox and CSS grid.</em></strong></p><h3>Conclusion</h3><p>Nightwatch.js is one of the most in-demand Selenium Javascript-based automation testing frameworks known for its simplicity and integrated features. In this blog, we have looked into Nightwatch.js installation and setup, along with a detailed walkthrough on configurations. Additionally, we have also leveraged our automation testing by adopting test coverage concepts and cross browser testing.</p><p>Hopefully, this Nightwatch.js tutorial will enable you to kickstart your journey in Nightwatch.js automation. TestMu AI (formerly LambdaTest) is an AI-native software testing cloud for web, mobile, and AI applications. Its GenAI-native testing agent, KaneAI, plans tests and writes test cases and automation from natural language, tickets, or docs. You can run them on 3000+ browser and OS combinations and 10,000+ real Android and iOS devices, and orchestrate them at scale with HyperExecute. <a href="https://www.testmuai.com/selenium-automation/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun07_sd&amp;utm_term=rd&amp;utm_content=webpage">Run your existing Selenium, Cypress, Playwright, and Puppeteer tests</a> across 3000+ browser and OS combinations in parallel.</p><p><strong>Happy testing!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b8ba0b81de7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Testing With Jasmine And Karma Using Selenium [Tutorial]]]></title>
            <link>https://haritaravindranath.medium.com/angular-testing-with-jasmine-and-karma-using-selenium-tutorial-d7add09e91c?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7add09e91c</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[jasmine]]></category>
            <category><![CDATA[karma]]></category>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Mon, 06 Jun 2022 17:15:37 GMT</pubDate>
            <atom:updated>2026-10-21T09:24:42.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*RvR52uYTGjq_Rr5TX6EZtg.jpeg" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/angular-testing-with-jasmine-and-karma/"><em>TestMu AI blog</em></a><em>.</em></p><p>Software testing is the best way to prevent software defects and plays an important role in the Software Development Life Cycle (SDLC). It is a critical step in software development, and can be achieved using various testing methods. Different testing approaches like Selenium automation testing, performance testing, and automated Unit testing can be chosen based on your application’s testing requirements.</p><p>Software testing is often considered to be a task of the QA team. However, developers can also write tests for their code to ensure the individual components or “units” of the software are working correctly and this is called Unit testing. As shown below, Angular is considered as the preferred test framework for automation testing. In this blog, we deep dive into how to perform Angular testing with Jasmine and Karma.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/0*_c_9IgoT_dIFxVWu.png" /><figcaption><a href="https://www.statista.com/statistics/1124699/worldwide-developer-survey-most-used-frameworks-web/"><em>Source</em></a></figcaption></figure><p>Various Unit testing frameworks for Selenium automation like Angular are available making it easy for developers to write their own Unit tests cases. Angular is considered to be one of the best web development frameworks. It comes with in-built Unit testing tools like Jasmine and Karma for automated Unit testing.</p><p>In this Angular testing tutorial, we discuss in-depth the benefits of Unit testing and how to perform Angular testing with Jasmine and Karma using Selenium.</p><p>With the assumption that you are comfortable with Typescript and Angular applications, let’s get started!</p><p>Now perform live interactive manual testing of your Angular websites on TestMu AI.</p><p><strong><em>Do you know </em></strong>CSS grab &amp; grabbing cursors <strong><em>adds support for the css 3 cursor property. It is useful to indicate that something can be grabbed (dragged to be moved).</em></strong></p><h3>Introduction to Unit Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*SvaQHPUXMdJVAoUq.png" /></figure><p>Unit testing is a type of software technique where individual units or components of an application are tested to ascertain they are working as expected. Unit tests are typically automation tests written and run by the software developer during the coding phase to test standalone modules of the application for its functional correctness. A unit can be an individual function, method, procedure, module, or object.</p><p>The main goal of Unit testing is to break the application source code into isolated units to identify, analyze and fix the defects arising from that particular unit. Testing a unit in isolation means testing without external resources like API endpoint or database. Instead, substitutes such as stub methods, mock objects or fakes will be used to harness a fake response and test code will be written based on that.</p><p><strong><em>Example:</em></strong><em> A library named Moxios is used to mock API calls using Axios.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*ND9gsP-v5KnJ7Wbk.png" /></figure><p>Developers and product owners often overlook Unit testing by pointing out limited development time and resources as reasons, making them proceed without it. And yes, this seldom works out. But the companies that are serious about the quality delivery of their product understands the significance of Unit testing and is diligent in enforcing it.</p><p>Since we are talking about Unit testing, it is also worth mentioning the most popular approaches that are used in combination with it — Test-Driven Development (TDD) and Behaviour-Driven Development (BDD).</p><h3>Benefits of Unit testing</h3><p>Unit testing is becoming more popular in the web development world. According to the reports presented by the fourth annual <strong>Developer Ecosystem Survey</strong> (2020) conducted by JetBrains, 77% of the developers stated that testing is an integral part of the development process in their companies or teams. Furthermore, 68% voted for Unit testing as the most popular approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vYV8AApx0kWACB1C.png" /><figcaption><a href="https://www.jetbrains.com/lp/devecosystem-2020/testing/"><em>Source</em></a></figcaption></figure><p>Larger or smaller, every project can enjoy the benefits of Unit testing. A few significant advantages are listed below:</p><ul><li>Helps identify and fix bugs early in the development cycle and save costs.</li><li>Forces developers to improve the design of implementations as it is difficult to write unit tests for poorly written code.</li><li>Ensures the developer that the new feature added is not breaking the existing code hence giving confidence in code quality.</li><li>Simplified debugging fails; only the latest code needs to be if the test fails debugged.</li><li>Aids in overall faster development.</li><li>Allows better refactoring of code.</li><li>Good Unit testing can even serve as project documentation. Developers, especially those who newly joined the team, can look at the unit tests to learn about the functionality provided by the unit, how to use it etc.</li></ul><h3>Limitations of Unit testing</h3><p>It is equally important to understand the limitations of Unit testing. A few are listed below:</p><ul><li>It is impossible to catch every error in the program using Unit testing as it cannot evaluate every execution path. It cannot catch integration errors, complex broad system errors or non-functional attributes like usability, scalability, performance etc.</li><li>The difficulty of setting up realistic and relevant unit tests. If they are not set correctly, it can diminish the value and accuracy of test results.</li><li>If the Unit test involves just passing input and verifying the output for a method, it tends to be easy to create. However, it is not so simple if it includes something more complex like interaction with an external resource.</li></ul><p><strong><em>Do you know </em></strong>CSS3 Colors<strong><em> is a small, lightweight and modular color library that allows you to describe RGB and HSLA with arrays, as well as set transparent colors via rgba() and hsla().</em></strong></p><h3>Unit testing With Angular Framework</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/0*sbpQMK9o_gohELBh.png" /></figure><p>Since Unit testing has become an integral part of development, all the major development frameworks now come with support for Unit testing. Numerous testing libraries and frameworks are available to reduce the amount of time taken to write tests.</p><p>In the further section of Angular testing with Jasmine and Karma tutorial, you will learn how to test Angular applications with Karma Testrunner and Jasmine framework using Selenium.</p><p>But before that, let us know and understand why we are using them.</p><h3>Why Karma?</h3><p>Karma is the default test runner for applications created using Angular CLI. Being a direct product of the AngularJS team, Karma is very well suited for testing Angular or any other JavaScript-based project. Running on Node.js, Karma test runner can be seamlessly integrated with testing frameworks like Jasmine, Mocha, QUnit and integration services like Jenkins, CircleCI, TravisCI etc. In addition, it allows you to run your automated tests on various browsers and devices.</p><p>Karma uses a configuration file to set the startup file, the testing framework, the reporters, the browser and other things. It aims to bring a productive testing environment to developers by spending less time on setting up the configurations but more time on coding. Additionally, there is also good online documentation.</p><p>The NPM package download trends show that even in 2021 Karma is the most popular Test Runner for Angular Testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sbFx7OctFZlT5OAc.png" /><figcaption><a href="https://www.npmtrends.com/ava-vs-karma-vs-protractor"><em>Source</em></a></figcaption></figure><h3>Why Jasmine?</h3><p>Jasmine is a testing framework for JavaScript that supports the<strong> Behavior-Driven Development</strong> (BDD) practice. It plays very well with Karma and is part of the default setup with Angular CLI. Jasmine is known to be feature-rich and provides easy integration with reporting. Also, it provides additional functions such as fakes, spies and pass-throughs. We will be performing Angular Testing with Jasmine.</p><p>Behaviour-Driven Development (BDD) is a testing practice that focuses on the application’s behavior. BDD allows you to write tests in human-readable (simple English) format so that even non-technical people can easily understand what is being tested. This plain English format used to write BDD test scenarios is known as the <strong>Gherkin </strong>language.</p><p>The BDD tests can act as living test documentation that is easy to maintain and can be consumed by all team members including product owners, business analysts, developers, testers, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*grNZ8E92aNTEAhTn.png" /></figure><p>We will be writing our unit tests using Jasmine following the BDD approach. Then using Karma test runner, we can trigger the test execution from the CLI. Karma also has a watch mode that can automatically detect changes in development files and re-runs the test. Don’t worry! You will reach a better understanding once you start writing the unit tests.</p><h3>Why Selenium?</h3><p>Although Selenium is a tool that needs no introduction among software testers, because this article is primarily aimed at developers, let us first specify <a href="https://www.testmuai.com/selenium/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun06_sd&amp;utm_term=sd&amp;utm_content=">what is Selenium</a>.</p><p>Selenium is a free open-source test automation framework that is used to automate web browsers. It allows you to validate websites and web apps across multiple devices, browsers and OS to ensure it is working properly as expected. Selenium Webdriver and Selenium Grid are the integral components of the Selenium automation framework.</p><p>If you are looking for ways to scale by running tests distributedly, Selenium Grid is the best choice. Selenium Grid allows you to run tests parallely on multiple machines (environments) against various browsers, OS and device combinations hence boosting the speed of the testing cycle without compromising on the test coverage.</p><p>In this Angular testing with Jasmine and Karma tutorial, we will be configuring the Jasmine framework with the online Selenium Grid provided by TestMu AI platform. TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications.</p><p>Now that you got a gist of the above discussed tools, let us move on to writing Unit test cases in an Angular application.</p><p>But before that let us set up a dummy project upon which we will be writing meaningful Unit tests.</p><p><strong><em>Check this out: </em></strong>CSS3 attr() function for all properties<strong><em>- With CSS Values and Units Level 3, the “attr()” function can be used on any CSS property, plus with non-string values (e.g., numbers and colors).</em></strong></p><h3>Setting up an example project using Angular, Karma and Jasmine</h3><p>You can find all the code samples used in this Angular testing tutorial from the <a href="https://github.com/harita-R/angular-unit-test">GitHub repository</a>. Let us begin by creating a new Angular app.</p><p>Following are my choice of tools.</p><ul><li>Angular CLI</li><li>Visual Studio Code as IDE</li></ul><p>You can run the below command to install Angular CLI globally.</p><pre>npm install -g <a href="http://twitter.com/angular/cli">@angular/cli</a></pre><p><strong>Step 1</strong>: Create a new Angular project using Angular CLI. This will take care of Jasmine and Karma configuration for us out-of-the-box.</p><p><strong>Step 2</strong>: Open the IDE, create a new project folder and run the following command in the terminal. Here, I am naming the project as “angular-unit-test”.</p><pre>ng new angular-unit-test</pre><p>The project is set up successfully with all the dependencies installed. The root folder structure now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*oIJXSYrHz_0OnNGU.png" /></figure><p>To run the test, pass the following command.</p><pre>```ng test</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skfDowa4yXuQwmmZlQJuiQ.png" /></figure><p>The test execution starts and a new browser instance gets opened. Observe the browser report and terminal logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KMHZaI1Lr5NQvVEA.png" /></figure><p><strong>Step 3</strong>: Let us start building our app by creating new components. For the demo, I will be creating a simple Angular app using Bootstrap containing the following components:</p><ul><li>Header</li><li>Footer</li><li>Login Form</li><li>Signup Form</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R8qeaLhaI1RYB45F.png" /></figure><p>Run the following command to generate new components using Angular CLI.</p><pre>ng g c folder_name/component_name</pre><p>All my components have been placed inside a folder named “components” in src/app. To create a component named “header”, run the following command:</p><pre>ng g c components/header</pre><p>The header component is created successfully. Notice that 4 files are auto-generated for every component — html,css, ts and spec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*mYW5UeWLR8JC2NVk.png" /></figure><p>We will be writing our Unit test inside the spec.ts file. By default, the file will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WAzs_p1mETU9RrC4.png" /></figure><p>Since explaining basic Angular things is out of this tutorial’s scope, I won’t be covering the app creation. Refer to the steps below to clone and set up my completed sample app.</p><pre>git clone <a href="https://github.com/harita-gr/MyStay_app.git">https://github.com/harita-gr/MyStay_app.git</a></pre><pre>npm install</pre><pre>npm start</pre><p><strong>Step 4</strong>: Configure testing in your Angular Project.</p><p>When we run the ng test, Angular takes the test configuration from the angular.json file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*VVfTegW7e7dmjKSX.jpg" /></figure><p>The test-related configuration mainly lies on the shoulder of these 2 files.</p><ul><li><strong>test.ts</strong> — also known as test entry file, this file is used to load all spec.ts files from the project for testing</li><li><strong>karma.conf.js</strong> — here we specify configurations like browser, port, report, online grid etc.</li></ul><p>Let us take a look at our <strong>test.ts</strong> file. This file is the entry point of tests for the application. You don’t have to make any changes to the <strong>test.ts</strong> file.</p><p>Let us quickly grasp what is going on here.</p><ul><li>At the beginning of the file, we are initializing our Angular test environment using all the imports.</li><li>After this, we find all the test files by matching their name against the regular expression (filename ending with spec.ts ) and load them.</li></ul><p><strong>TestBed </strong>is also initialized in this file. If you are wondering what TestBed is, it is a powerful Unit testing tool provided by Angular. It creates a dynamically constructed test module that emulates an Angular NgModule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3dPPZB4TsK-FhDZ_.png" /></figure><p>Now let us move on to the <strong>karma.conf.js</strong> file. But as you can notice, most of them are self-explanatory. So let us quickly go through some of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5NaSWvnLj3WssA7I.png" /></figure><ul><li><strong>frameworks </strong>— Here we set our test automation framework which is Jasmine by default. But you can go on and change it as per your project requirement.</li><li><strong>reporters </strong>— This is where we set our reporters. You can modify or add new ones.</li><li><strong>autoWatch </strong>— If this is set to true, the test will run in watch mode. When you change any file and save it, tests are re-build and re-run.</li><li><strong>port </strong>— This is where you can set your port.</li><li><strong>browsers </strong>-Here you can set the browsers on which the tests should run. By default it is Chrome. But you can install and add new browser launchers.</li></ul><p>If you are running your tests on a local machine, this configuration is good enough. But since we will be using an online grid for running our tests, we need to make some additional configurations which are as follows.</p><ol><li>Set the webdriver configuration for running in the TestMu AI host.We need to pass a grid hostname, port, and user and access key. You can fetch your unique username and access key by <a href="https://accounts.lambdatest.com/register?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun06_sd&amp;utm_term=sd&amp;utm_content=register">creating a free </a>TestMu AI account and navigating to your profile page.</li></ol><pre>// Lambdatest grid hostname and port<br>  var webdriverConfig = {<br>    hostname: &quot;hub.lambdatest.com&quot;,<br>    port: 80,<br>    user: process.env.LT_USERNAME || &#39;YOUR_USERNAME&#39;,<br>    accessKey: process.env.LT_ACCESS_KEY || &#39;YOUR_ACCESSKEY&#39;,<br>  };</pre><p>2. As our tests will be run on a cloud grid, we no longer need the browser launcher set up. Instead, install the webdriver launcher and add it as a plugin.</p><pre>npm install -D karma-webdriver-launcher</pre><pre>plugins: [<br>      require(&quot;karma-jasmine&quot;),<br>      require(&quot;karma-webdriver-launcher&quot;),<br>      require(&quot;karma-jasmine-html-reporter&quot;),<br>      require(&quot;karma-coverage&quot;),<br>      require(&quot;<a href="http://twitter.com/angular">@angular</a>-devkit/build-angular/plugins/karma&quot;),<br>    ],</pre><p>3. Now, we need to define our custom launchers. TestMu AI provides you access to 3000+ browsers and 10,000+ real devices. So you no longer need to restrict yourself by testing only on one device/browser/OS like when you test locally. I am configuring the tests to run in Chrome, Firefox and Edge in a custom browser version and OS.The configuration needs to be done similar to the object given below.</p><pre>customLaunchers: {<br>      chrome: {<br>        base: &quot;WebDriver&quot;,<br>        config: webdriverConfig,<br>        browserName: &quot;chrome&quot;,<br>        platform: &quot;windows 8.1&quot;,<br>        version: &quot;71.0&quot;,<br>        build:&#39;Unit testing in Angular&#39;, //Build name<br>        name: &quot;Unit test&quot;, // Test name<br>        pseudoActivityInterval: 5000, // 5000 ms heartbeat<br>      },</pre><p>You can generate Selenium Capabilities using TestMu AI<a href="https://www.testmuai.com/capabilities-generator/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun06_sd&amp;utm_term=sd&amp;utm_content=webpage"> Desired Capability</a> Generator to find your custom combination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sU2XCvIbQFn_6-Sf.png" /></figure><p>4. Also update the browser name w.r.t the custom launcher.</p><pre>browsers: [&quot;chrome&quot;],</pre><p>That’s all! The final karma.conf.js file now looks like this.</p><pre>// Karma configuration file, see link for more information<br>// <a href="https://karma-runner.github.io/1.0/config/configuration-file.html">https://karma-runner.github.io/1.0/config/configuration-file.html</a><br> <br>module.exports = function (config) {<br>  // Lambdatest grid hostname and port<br>  var webdriverConfig = {<br>    hostname: &quot;hub.lambdatest.com&quot;,<br>    port: 80,<br>    user: process.env.LT_USERNAME || &#39;YOUR_USERNAME&#39;,<br>    accessKey: process.env.LT_ACCESS_KEY || &#39;YOUR_ACCESSKEY&#39;,<br>  };<br> <br>  config.set({<br>    basePath: &quot;&quot;,<br>    // hostname: &#39;localhost&#39;, // hostname, where karma web server will run<br>    frameworks: [&quot;jasmine&quot;, &quot;<a href="http://twitter.com/angular">@angular</a>-devkit/build-angular&quot;],<br>    plugins: [<br>      require(&quot;karma-jasmine&quot;),<br>      require(&quot;karma-webdriver-launcher&quot;),<br>      require(&quot;karma-jasmine-html-reporter&quot;),<br>      require(&quot;karma-coverage&quot;),<br>      require(&quot;<a href="http://twitter.com/angular">@angular</a>-devkit/build-angular/plugins/karma&quot;),<br>    ],<br>    client: {<br>      jasmine: {},<br>      clearContext: false, // leave Jasmine Spec Runner output visible in browser<br>    },<br>    jasmineHtmlReporter: {<br>      suppressAll: true, // removes the duplicated traces<br>    },<br>    coverageReporter: {<br>      dir: require(&quot;path&quot;).join(__dirname, &quot;./coverage/angular-unit-test&quot;),<br>      subdir: &quot;.&quot;,<br>      reporters: [{ type: &quot;html&quot; }, { type: &quot;text-summary&quot; }],<br>    },<br>    reporters: [&quot;progress&quot;, &quot;kjhtml&quot;],<br>    port: 9876,<br>    colors: true,<br>    logLevel: config.LOG_INFO,<br>    autoWatch: true,<br>    browsers: [&quot;chrome&quot;,&quot;firefox&quot;,&quot;edge&quot;],<br>    singleRun: false,<br>    restartOnFileChange: true,<br> <br>    customLaunchers: {<br>      chrome: {<br>        base: &quot;WebDriver&quot;,<br>        config: webdriverConfig,<br>        browserName: &quot;chrome&quot;,<br>        platform: &quot;windows 8.1&quot;,<br>        version: &quot;71.0&quot;,<br>        build:&#39;Unit testing in Angular&#39;, //Build name<br>        name: &quot;Unit test&quot;, // Test name<br>        pseudoActivityInterval: 5000, // 5000 ms heartbeat<br>      },<br>      firefox: {<br>        base: &quot;WebDriver&quot;,<br>        config: webdriverConfig,<br>        browserName: &quot;Firefox&quot;,<br>        platform: &quot;windows 10&quot;,<br>        version: &quot;91.0&quot;,<br>        build:&#39;Unit testing in Angular&#39;,<br>        name: &quot;Unit test&quot;,<br>        pseudoActivityInterval: 5000, // 5000 ms heartbeat<br>      },<br>      edge: {<br>        base: &quot;WebDriver&quot;,<br>        config: webdriverConfig,<br>        browserName: &quot;MicrosoftEdge&quot;,<br>        platform: &quot;windows 10&quot;,<br>        version: &quot;93.0&quot;,<br>        build:&#39;Unit testing in Angular&#39;,<br>        name: &quot;Unit test&quot;,<br>        pseudoActivityInterval: 5000, // 5000 ms heartbeat<br>      }<br>    },<br>  });<br>};</pre><p>5. Let us test our configuration by triggering our test runner.</p><pre>ng test</pre><p>Our test will start running on a cloud grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xl4qHrgh0g-eaw9W.png" /></figure><p>Go to the TestMu AI Automation Dashboard to access the results of your test execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rU8HXyWmY7RKhiwc.png" /></figure><p>This <a href="https://www.youtube.com/watch?v=BQ-9e13kJ58&amp;list=PLZMWkkQEwOPl0udc9Dap2NbEAkwkdOTV3?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun06_sd&amp;utm_term=sd&amp;utm_content=tutorial_video">Selenium JavaScript testing tutorial</a> for beginners and professionals will help you learn everything you need to know to work with JavaScript for Selenium automation testing.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBQ-9e13kJ58%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBQ-9e13kJ58&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBQ-9e13kJ58%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e54781ed0ee5ce356b36f713e75aef2a/href">https://medium.com/media/e54781ed0ee5ce356b36f713e75aef2a/href</a></iframe><h3>Writing your first Angular Unit Test using Jasmine</h3><p>We have successfully completed our test configuration.In this section of Angular testing with Jasmine, we will write unit test cases for Angular using Jasmine.</p><h3>Understanding the Test Run flow</h3><p>As mentioned earlier, associated with each component, a spec.ts file will be generated inside which we will be writing our test case. The default spec file generated for the App component app.component.spec.ts is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6A0mERSrx3eOWzcz.png" /></figure><p>Let us understand the test run flow.</p><ul><li>Import all the tools we will be going to use like TestBed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ihudAmi5o2ZOGEic.png" /></figure><ul><li>Import all of the dependencies for this component.</li><li>To start our test block, we use the “<strong>describe</strong>” function, the title of which will be matching the component name under test.describe(string, function)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/0*hQJ7HiwIvwCJMNKB.png" /></figure><ul><li>Then we have the “it” function, which is used to define test cases. Meaningful names can be given to the test case.it(string, function)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*omEiPm2m5dvZdiBC.png" /></figure><ul><li>Additionally, we also have setup and teardown functions which will be run before or after each “it” function. Here, “<strong>beforeEach</strong>” is defined which contains async code. The purpose of this is to await till all the async code is finished before continuing. This function is called before each test specification (it function) is run.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/0*Jo2twv9q2Dt9RnPm.png" /></figure><p>We have three Unit tests over here:</p><ol><li>First one verifies that the app is created successfully.</li><li>Second one verifies the app title is equal to the expected value.</li><li>Third one verifies that the title is rendered.</li></ol><p>The overall run flow can be visualized as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/0*_nTkhxQEX_2Sgdo2.png" /></figure><h3>Writing Unit test cases for Components</h3><p>Now that you have an idea about how the test run flows, let us start by writing Unit test cases for the header component. To write meaningful tests, it is crucial to identify what you need to test.</p><p>For the header component, I want to verify the following cases:</p><ol><li>It should display a logo containing the text “My Stay”.</li><li>It should have six nav links.</li><li>It should navigate to the register page by clicking the signup/login button.</li></ol><p>The code for testing the header component is shown below.</p><pre>//header.component.spec.ts<br> <br>import { ComponentFixture, TestBed, tick } from &#39;@angular/core/testing&#39;;<br>import { By } from &#39;@angular/platform-browser&#39;;<br>import { Location } from &quot;@angular/common&quot;;<br> <br>import { HeaderComponent } from &#39;./header.component&#39;;<br> <br>describe(&#39;HeaderComponent&#39;, () =&gt; {<br>  let component: HeaderComponent;<br>  let fixture: ComponentFixture&lt;HeaderComponent&gt;;<br> <br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({<br>      declarations: [ HeaderComponent ]<br>    })<br>    .compileComponents();<br>  });<br> <br>  beforeEach(() =&gt; {<br>    fixture = TestBed.createComponent(HeaderComponent);<br>    component = fixture.componentInstance;<br>    fixture.detectChanges();<br>  });<br> <br>  it(&#39;should create&#39;, () =&gt; {<br>    expect(component).toBeTruthy();<br>  });<br> <br>  it(&#39;should display logo containing text &quot;My Stay&quot;&#39;, () =&gt; {<br>     const logoText =fixture.debugElement.query(By.css(&#39;.navbar-brand&#39;)).nativeElement;<br>     expect(logoText.textContent).toBe(&#39;My Stay &#39;);<br>  });<br> <br>  it(&#39;should contain 6 nav links&#39;, () =&gt; {<br>    const navLinks = fixture.debugElement.queryAll(By.css(&#39;li.nav-item&#39;));<br>    expect(navLinks.length).toEqual(6);<br>  });<br> <br>  it(&#39;navigates to register page on clicking signup/signin button&#39;, () =&gt; {<br>    const location: Location = TestBed.inject(Location);<br>    const button =fixture.debugElement.query(By.css(&#39;button.btn&#39;)).nativeElement;<br>    button.click();<br>    expect(location.path()).toBe(&#39;/user-register&#39;);<br>  });<br>});</pre><p>Now I want to test my footer component. Following are the test cases:</p><ol><li>It should contain the copyright text</li><li>It should contain three social media contact buttons</li></ol><p>The code for testing footer component is shown below:</p><pre>//footer.component.spec.ts<br> <br>import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;;<br>import { By } from &#39;@angular/platform-browser&#39;;<br> <br>import { FooterComponent } from &#39;./footer.component&#39;;<br> <br>describe(&#39;FooterComponent&#39;, () =&gt; {<br>  let component: FooterComponent;<br>  let fixture: ComponentFixture&lt;FooterComponent&gt;;<br> <br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({<br>      declarations: [ FooterComponent ]<br>    })<br>    .compileComponents();<br>  });<br> <br>  beforeEach(() =&gt; {<br>    fixture = TestBed.createComponent(FooterComponent);<br>    component = fixture.componentInstance;<br>    fixture.detectChanges();<br>  });<br> <br>  it(&#39;should create&#39;, () =&gt; {<br>    expect(component).toBeTruthy();<br>  });<br> <br>  it(&#39;should contain copyright text&#39;, () =&gt; {<br>    const text =fixture.debugElement.query(By.css(&#39;.copyright&#39;)).nativeElement;<br>    expect(text.textContent).toContain(&#39;Copyright&#39;);<br>  });<br> <br>  it(&#39;should contain 3 social media contact buttons &#39;, () =&gt; {<br>    const btns = fixture.debugElement.queryAll(By.css(&#39;a.btn&#39;));<br>    expect(btns.length).toEqual(3);<br>  });<br>});</pre><p>Lastly, I want to test my Login Component. Following are the test cases:</p><ol><li>It should be able to login by entering an email and password and submitting form</li><li>It should route to register page by clicking the “Sign Up here” link</li></ol><p>The code for testing the login component is shown below.</p><pre>//login.component.spec.ts<br> <br>import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { By } from &#39;@angular/platform-browser&#39;;<br>import { Location } from &quot;@angular/common&quot;;<br> <br>import { LoginComponent } from &#39;./login.component&#39;;<br> <br>describe(&#39;LoginComponent&#39;, () =&gt; {<br>  let component: LoginComponent;<br>  let fixture: ComponentFixture&lt;LoginComponent&gt;;<br> <br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({<br>      imports: [FormsModule ],<br>      declarations: [LoginComponent],<br>    }).compileComponents();<br>  });<br> <br>  beforeEach(() =&gt; {<br>    fixture = TestBed.createComponent(LoginComponent);<br>    component = fixture.componentInstance;<br>    fixture.detectChanges();<br>  });<br> <br>  it(&#39;should create&#39;, () =&gt; {<br>    expect(component).toBeTruthy();<br>  });<br> <br>  it(&#39;should be able to login by entering email and password and submitting form&#39;, () =&gt; {<br>    component.User[&#39;email&#39;] = &#39;test@test.com&#39;;<br>    component.User[&#39;password&#39;] = &#39;123456789&#39;;<br>    const loginBtn = fixture.debugElement.query(By.css(&#39;button.login-btn&#39;)).nativeElement;<br>    loginBtn.click();<br>    expect(component.submitted).toBeTrue;<br>  });<br> <br> <br>  it(&#39;should route to register page by clicking “Sign Up here” link&#39;, () =&gt; {<br>    const location: Location = TestBed.inject(Location);<br>    const link =fixture.debugElement.query(By.css(&#39;a&#39;)).nativeElement;<br>    link.click();<br>    expect(location.path()).toBe(&#39;/user-register&#39;);<br>  });<br>});</pre><p>Now it is time to run the test cases. Execute the following command.</p><pre>ng test</pre><p>Go to the TestMu AI Automation Dashboard. You can notice the test starts running on a cloud-based Selenium grid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XY1Q95S5v_Nnnqlb.png" /></figure><p>Go to Automation Logs to see the detailed report of your tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m1ofcw7wpbf-IMLg.png" /></figure><p>We have successfully executed our Unit test cases in Angular.</p><p>Navigate to the TestMu AI<a href="https://accounts.lambdatest.com/login?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun06_sd&amp;utm_term=sd&amp;utm_content="> Analytics Dashboard</a> to view test performance metrics of your Unit tests. The Test Overview will provide a screenshot of tests with consistent behavior. Meanwhile, the Test Summary will show the total number of passed or failed tests, and any completed or queued tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vqxjU-OOIsRxKodH.png" /></figure><h3>Best Practices to Improve Unit testing</h3><p>While performing Unit testing, here are some best practices one should keep in mind.</p><ol><li>Follow a consistent naming convention and test one code at a time</li><li>Make sure that there is a corresponding unit test case to every module</li><li>Before moving on to the next phase, all the bugs should be fixed. So you can end up with a clean and reliable code for committing.</li><li>Continuously refactor test code</li><li>Finally, focus more on the tests that affect the behavior of the system.</li></ol><p>Here’s a short glimpse of the Selenium JavaScript 101 certification from TestMu AI:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDQwSRfCkhSM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDQwSRfCkhSM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDQwSRfCkhSM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/51d0063b079d7124de1d91a471c04a0f/href">https://medium.com/media/51d0063b079d7124de1d91a471c04a0f/href</a></iframe><h3>Conclusion</h3><p>In this Selenium JavaScript tutorial on Angular testing with Jasmine and Karma, we learnt how to perform Unit testing in Angular framework with Jasmine and Karma test runner using Selenium. We also covered practical implementation.</p><p>As the code base keeps on growing it becomes time-consuming to execute the unit tests locally in our system in addition to the limited scope test coverage. So, we utilized the online Selenium Grid provided by TestMu AI platform to leverage our test execution by running the unit tests parallelly across multiple custom-configured environments.</p><p>I hope you found this Angular testing tutorial useful!</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7add09e91c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Speed Up JavaScript Testing With Selenium and WebDriverIO?]]></title>
            <link>https://haritaravindranath.medium.com/how-to-speed-up-javascript-testing-with-selenium-and-webdriverio-84580cec010e?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/84580cec010e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Fri, 03 Jun 2022 14:09:14 GMT</pubDate>
            <atom:updated>2026-10-21T09:23:46.420Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*UciQxRcy4ybQAcQV8NtfTA.jpeg" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/speed-up-javascript-testing-with-selenium-and-webdriverio/"><em>TestMu AI blog</em></a><em>.</em></p><p>Automation testing has become an integral part of the Agile way of software development. As the application grows, it becomes crucial to have a reliable testing framework to cope with the development velocity, detect the bugs at an early stage, and ensure quality. However, to achieve greater speed, scalability, wider test coverage, and a better ROI, it becomes important to adopt various testing strategies. <a href="https://www.testmuai.com/learning-hub/webdriverio/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun03_sd&amp;utm_term=sd&amp;utm_content=learning_hub">WebdriverIO</a> is a JavaScript testing framework extensively adopted by top-companies worldwide to simply and concisely fulfill all their testing needs quickly and efficiently.</p><p>Built on top of NodeJS and Selenium Webdriver (W3C WebDriver) API, WebdriverIO supports both web and mobile application testing. Since you are taking your time to read this article, it means you might fall into any of the below categories:</p><ul><li>You might be just starting with WebdriverIO and want to lay the foundation right to build a robust framework for JavaScript testing.</li><li>You are already using WebdriverIO and seeking out how to optimize your framework and speed up the JavaScript testing.</li><li>You might be keen on getting some idea on how to level up your JavaScript with Selenium automated testing game and extract more out of the framework.</li></ul><p>In this article, we will be trying to cater to each of these requirements and see how to speed up JavaScript testing. With the expectation that at least a few of the tips mentioned here will save your day, let’s get started!</p><h3>Best Practices to Adopt While Developing WebdriverIO Framework</h3><p>Honestly, setting up an automated testing framework is not an easy task, especially when you are using JavaScript with Selenium. But once the foundation is laid right, with timely maintenance, the benefits that can be reaped are limitless.</p><p>In this section, we will be discussing some key points that need to be considered, especially if you are just starting up with the WebdriverIO framework setup for JavaScript testing. Let’s look into it!</p><p><strong>1.WebdriverIO Version</strong></p><p>First and foremost, go for the latest version of WDIO, i.e., currently v6, released in early 2020. According to official documentation, LTS will be provided for v5 till April 2021, and v4 is currently deprecated. Now let’s see some of the desirable features that v6 has to offer.</p><p><strong>a) Natively supports Puppeteer</strong></p><p>To run a local test case, you are free to switch between Puppeteer and WebdriverIO API as you wish. Also, you won’t need to download the browser driver anymore. With WebdriverIO, you can check if a browser driver is running and accessible at localhost:4444/. In case it doesn’t, check if it uses Puppeteer as a fallback. Being able to access Puppeteer in your tests allows you to:</p><ul><li>Leverage the Chrome DevTools protocol capabilities, with a much richer set of automation features.</li><li>Run commands on Puppeteer much faster. Hence it can help speed up local execution.</li></ul><p><strong>b) Performance Improvements</strong></p><p>This has been one of the primary design goals of WDIO v6. It has also come with many internal improvements that will speed up test execution and lower CPU and memory usage.</p><p>And there’s a lot more. You can always refer to the <a href="https://webdriver.io/blog/2020/03/26/webdriverio-v6-released.html">WebdriverIO official documentation</a> to know more about WebdriverIO v6.</p><p><strong>2. Page Object Model (POM)</strong></p><p>POM is a framework design pattern widely adopted by Agile practitioners for easy test script maintenance and enhanced code reusability. Implementing an approach like POM will help you efficiently manage your locators, reduce duplication, and make your framework more programmer-friendly.</p><p>So even if this directly won’t speed up your execution time, in the long run, the POM approach can save your time spent on creating and maintaining test scripts for JavaScript testing. You can refer to the <a href="https://webdriver.io/docs/pageobjects.html">WebdriverIO Page Object Model</a> page to know more about it.</p><p><strong>3. Create Helper Methods</strong></p><p>Now, this is also linked with code reusability and ease of maintenance. Fundamentally, the idea is to wrap the code for commonly performed actions — like logging in, clicking on something, waiting for a result, logging out, etc. into a method so that they can be shared and reused by all scripts.</p><p>Also, you can add parameters to customize these helper methods to suit various function call needs.</p><p><strong>4. Don’t test the same functionality twice</strong><br>To speed up the testing, we should be strategic in terms of test coverage. Reducing the duplicate and avoidable scenarios directly helps to bring the test case count down.</p><p>Needless to explain more, the lower the test case count, the faster the execution result.</p><p><strong>5. Avoid Hardcoding URLs</strong></p><p>In WebdriverIO, we have a configuration file wdio.conf.js, which aids us in specifying the location of the tests, frameworks you want to use, reporters, browsers, and all other general configs of the project.</p><p>Another useful option is to configure the baseUrl of the application here so that we don’t need to specify it every time in our test scripts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V9E-dLXdv9e5wIcx.png" /></figure><p>But generally, in most cases, we might need to run the application in multiple environments like — development, QA, staging, production, etc., each having different URLs. In that case, we can easily configure the URLs by declaring an environment variable and passing the detail of the environment/URL in which the test should run along with the test run command.</p><p>The configuration steps are briefly explained below:</p><p><strong>Step 1:</strong> Create a separate file to maintain the URLs and export them. Here we have created a file named ‘wdio.config.url.js’ (Give any name of choice)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/0*Qsis7egES1bokMQF.png" /></figure><p><strong>Step 2:</strong> The remaining settings are to be done in the wdio.conf.js file. First of all, require the URL file.</p><pre>const urls = require(‘./wdio.config.url’)</pre><p><strong>Step 3:</strong> Create an environment variable to pass the URL values.</p><pre>const ENV = process.env.ENV</pre><p><strong>Step 4:</strong> Create a condition to check if the value passed for ENV is valid.</p><pre>`if (!ENV || ![&#39;qa&#39;, &#39;dev&#39;, &#39;live&#39;].includes(ENV)) {<br>    console.log(&#39;Invalid environment! Please select : ENV=qa|dev|live&#39;)<br>    process.exit()<br>}</pre><p><strong>Step 5:</strong> Now, inside exports.config change the baseUrl to match the environment variable.</p><pre>baseUrl: url[process.env.ENV],</pre><p><strong>Step 6:</strong> That’s pretty much it. Now along with the test run command, pass the value for ENV.</p><pre>npm run test ENV=dev</pre><p>Here, the URL for DEV will be mapped, and the test starts running. If any invalid value is passed or the value of ENV is skipped, corresponding logs will be generated as per the check condition we created.</p><p><strong>6. Writing a good test script</strong></p><p>Finally, it all comes to writing a good test script. Following are a few good practices that you can adopt while designing your test script while performing JavaScript testing.</p><ul><li>Writing only one test case in a test file. This helps in keeping the test cases independent of each other, analyzing failure, and also aids in parallel testing.</li><li>Keeping it short or atomic. Reduce the number of steps to below 20 (there is no golden rule). Make use of helper methods.</li></ul><p>You can take this certification as proof of expertise in the field of test automation with JavaScript to empower yourself and boost your career.</p><p>Here’s a short glimpse of the Selenium JavaScript 101 certification from TestMu AI:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDQwSRfCkhSM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDQwSRfCkhSM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDQwSRfCkhSM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/47884db56522c14ec16c9b89dbeb083b/href">https://medium.com/media/47884db56522c14ec16c9b89dbeb083b/href</a></iframe><p><strong><em>Have you read about </em></strong>CSS Paint API<strong><em>? Css-paint-api is a Python library that lets you generate images used by CSS using code.</em></strong></p><h3>Optimize Your Framework to Speed Up JavaScript Test Execution</h3><p>So far, we have covered some of the best practices that can be adopted while developing the automated testing framework. Here, we will be discussing how we can optimize the WebdriverIO framework to speed up JavaScript testing while using JavaScript with Selenium.</p><p>Let’s look into some possible factors that can slow down the testing and methods that can be adopted.</p><p><strong>1. Parallel Testing</strong></p><p>As the application features grow, so does the test count. It becomes more and more vital to enhance the execution speed and reduce overall execution time. One way of achieving this is through parallel testing, i.e., running your test scripts concurrently.</p><p>To enable parallel testing, adjust the maxInstances property in your config file. See the below sample code.</p><pre>exports.config = {<br>            // ...<br>            // set maxInstance for all browser<br>            maxInstances: 3,<br>            // ...<br>            capabilities: [{<br>                browserName: &#39;firefox&#39;<br>            }, {<br>                browserName: &#39;chrome&#39;<br>            }],<br>            // ...<br>        }</pre><p>Here the maxInstances is set to 3, and 2 capabilities are mentioned (Chrome, Firefox). The math is simple. The WDIO test runner will spawn 6 processes, i.e., 3 test files will run simultaneously in the 2 browsers. You can adjust the values according to your requirements.</p><p><strong>2. Disabling screenshots</strong></p><p>Screenshots are often our saviors when it comes to debugging. But it also comes with the cost of execution time and slowing down your tests. Hence, the suggestion is to enable screenshots only when test failure occurs instead of taking screenshots for each and every step.</p><p>This <a href="https://webdriver.io/docs/docs/rpii-wdio-html-reporter.html#to-take-a-screenshot-after-any-test-fails">WebdriverIO official documentation on the screenshot</a> will guide you on how to implement this using Hooks.</p><p><strong>3. Error Logging</strong></p><p>Configuring error logging doesn’t have any direct impact on execution speed up. However, the idea is to enable logs only when some error occurs, hence keeping the log data more relevant, assisting us in quick debugging.</p><p>The level of logging verbosity can be set in the wdio.conf.js file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/0*VbM2lyNqPnm9k0Wg.png" /></figure><p><strong>4. Use the right wait methods</strong></p><p>WebdriverIO provides us with various methods to assert wait in the program. It’s good to have an idea about which is to be used when and most importantly, which to avoid.</p><p><strong>a) pause()</strong></p><p>This method pauses execution for a specific amount of time. To avoid flaky test results, it is recommended not to use this command to wait for an element to show up, a page to load, or an action to happen. It is better to use commands like waitUntil, waitForExist, or other waitFor* commands.</p><pre>```browser.pause(milliseconds)<br></pre><p><strong>b) waitUntil()</strong></p><p>This wait command is your universal weapon if you want to wait on something. It expects a condition and waits until that condition is fulfilled with a truthy value.</p><pre>browser.waitUntil(condition, { timeout, timeoutMsg, interval })</pre><p><strong>c) waitFor*</strong></p><p>WebdriverIO offers many waitFor APIs, which helps to wait until an element is displayed, exists, clickable, etc.</p><ul><li>waitForClickable</li><li>waitForDisplayed</li><li>waitForEnabled</li><li>waitForExist</li></ul><p>Using the waitUntil() or waitFor* methods will make the script performance better. As the elements can be accessed as soon as they are available, and no extra waiting time is required.</p><p>Do check out the official <a href="https://webdriver.io/docs/api.html">WebdriverIO API documentation</a> for more information.</p><p><strong>5. Use headless browsers and drivers</strong></p><p>A headless browser is a browser that does not have a user interface. Headless testing is a way of running your test cases without browser UI, making your script run faster. This is an option you can consider if you don’t need a real browser for testing or using CI/CD.</p><p>And no need to worry! You will still be able to capture screenshots and see how your application looks in headless mode. Debugging can be done as effectively. In WDIO, by adding a few arguments in your config file, you can adopt the headless version of your favorite browser.</p><p><strong>a) For Firefox</strong></p><pre>browserName: &#39;firefox&#39;,<br>&#39;moz:firefoxOptions&#39;: {<br>    args: [&#39;-headless&#39;]<br>},</pre><p><strong>b) For Chrome</strong></p><pre>browserName: &#39;chrome&#39;,        <br>        &#39;goog:chromeOptions&#39;: {        <br>            args: [&#39;--headless&#39;, &#39;--disable-gpu&#39;]<br>        }<br></pre><p><strong><em>Check this out: </em></strong>:placeholder-shown CSS pseudo-class<strong><em>- Form elements sometimes provides a hint to the user on type of input they should give. Example, the HTML5 placeholder attribute. :input:placeholder-shown matches an element that is showing such placeholder text.</em></strong></p><h3>Further Enhancements to Your Test Framework</h3><p>WebdriverIO is an extremely feature-rich framework that provides tight integration with various services. This includes Jenkins, Bamboo, along with Docker for CI/CD implementations, Applitools for Visual Testing, TestMu AI for Cross Browser Testing, etc. In this section, we will talk about a few of the widely executed strategies while using JavaScript with Selenium that will level up your automated JavaScript testing.</p><p><strong>1) Automation Testing using CI/CD Pipeline</strong></p><p>To achieve speedy delivery with feedback on quality, it is crucial to integrate the automated testing into the CI/CD (Continuous Integration/Continuous Delivery) pipeline. This helps in enabling Continuous Testing.</p><p>WebdriverIO provides tight integration with CI systems like Jenkins. Being open-source, Jenkins is widely preferred in the automation testing world. With some quick and easy steps, Jenkins integration can be achieved in your WebdriverIO framework. Do check out the <a href="https://webdriver.io/docs/jenkins.html">Jenkins official guide</a> for Jenkins set-up!</p><p>Another favored strategy is to integrate Jenkins with container technologies like Docker. With the advent of Docker, practically all necessary application dependencies can be containerized. With this <a href="https://webdriver.io/docs/docs/wdio-docker-service.html">WDIO-Docker service</a>, you may run your application container in your CI and in complete isolation.</p><p><strong>2) Cross Browser Testing with Selenium Grid</strong></p><p>To stay ahead in a highly competitive market, it is our duty as testers to ensure the application’s quality in all scenarios, i.e., the app should behave as expected across all platforms, browsers, and devices without crashing. This is where test coverage and cross browser testing comes into the picture.</p><p>When it comes to distributed test execution, <a href="https://www.testmuai.com/selenium-automation/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun03_sd&amp;utm_term=sd&amp;utm_content=webpage">Cloud Selenium Grid</a> is always a good call. It can run test cases on different versions of browsers and different operating systems simultaneously. While using JavaScript with Selenium, you can use Selenium Grid along with the right cloud-based solution provider for cross browser testing. This could be an optimal strategy that you can deploy to assure quality.</p><p>TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications. Moreover, you can choose from a wide range of Windows and Mac operating systems, along with all legacy and latest browsers.</p><p>WedriverIO provides you service to seamlessly integrate TestMu AI into your framework through a few quick and easy steps. Let’s take a look!</p><p><strong>Step 1:</strong> In your project terminal, give the following command to save TestMu AI service as a devDependency.</p><pre>npm i wdio-lambdatest-service --save-dev<br></pre><p><strong>Step 2:</strong> Create a free account or log in to your TestMu AI<a href="https://accounts.lambdatest.com/login?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun03_sd&amp;utm_term=sd&amp;utm_content=it_sign_up"> account</a> and fetch your unique username and access key. You can fetch the details from the Profile section.</p><p><strong>Step 3:</strong> Now let’s make some edits to the config file. In your wdio.conf.js file</p><pre>user= process.env.LT_USERNAME || &quot;myusername&quot;,<br>key= process.env.LT_ACCESS_KEY || &quot;1234567890&quot;,<br> <br>exports.config = {<br> <br>    user,<br>    key,<br>    logFile : &#39;./logDir/api.log&#39;,<br>    services: [<br>        [&#39;lambdatest&#39;, {<br>            tunnel: true<br>        }]<br>    ],<br>    hostname: &#39;hub.lambdatest.com&#39;,<br>    path: &#39;/wd/hub&#39;,<br>    port: 80,<br>    capabilities: [{<br>        build: ‘WebdriverIO-RemoteSelenium-Test’<br>        maxInstances: 5,<br>        browserName: &#39;chrome&#39;,<br>        acceptInsecureCerts: true,<br>        network: true,<br>        video: true,<br>        visual: true,<br>        console: true<br> <br>    }],</pre><p>These are the additional configurations to be done:</p><ul><li>Pass your access token and user details by creating two variables, <strong>user</strong> and <strong>key</strong>.</li><li>Set the tunnel as true to enable routing connections from TestMu AI cloud through your computer.</li><li>Set the <strong>hostname</strong> corresponding to TestMu AI</li><li>Optionally, you can also enable report formats like video recording, console, network logs, etc., to be true.</li></ul><p><strong>Step 4:</strong> Run your tests. Use the command appropriate to you.</p><pre>npx wdio wdio.conf.js</pre><p>The test starts running, and logs can be observed in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a3VtdipDwKvzWIAa.png" /></figure><p>To observe live running status, go to your Automation dashboard in TestMu AI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sb-8J_FkOgNjUDN_.png" /></figure><p>We can analyze individual test run reports from Automation Logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SCAwwKoxshRIdnWS.png" /></figure><p>We have successfully run our test cases using an automated cross browser testing solution provided by TestMu AI through a hassle-free experience!</p><p><strong><em>Do you know </em></strong>CSS overscroll-behavior<strong><em> lets you control the way the contents of a scroll container scrolls when its position in the browser window is larger than or equal to the scrollport’s size.</em></strong></p><h3>Conclusion</h3><p>Automation was introduced to accelerate the testing process and identify development bugs at the early stage. More and more companies are coming out from the shell of the traditional way of manual testing and adopting a more “shift left” approach focusing on how to leverage the benefits of automated testing in their development process.</p><p>In this article, we have looked into some of the best practices to adopt for building a robust framework using WebdriverIO while using JavaScript with Selenium. We have also discussed various methods to optimize the performance by not only reducing execution time by speeding up the test but also debugging as well as maintenance time.</p><p>Additionally, we have also covered a few of the best strategies to stay ahead, like CI/CD implementation and cross browser testing. Empowered by TestMu AI, we utilized a cloud-based solution for remote Selenium Grid to achieve <a href="https://www.testmuai.com/blog/what-is-parallel-testing-and-why-to-adopt-it/">parallel cross browser testing</a> across multiple platforms.</p><p>You can also checkout how to perform manual browser testing on TestMu AI platform.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhJ-eP8TcGuY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhJ-eP8TcGuY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhJ-eP8TcGuY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/34ab070ba251a6749108b727a56df81d/href">https://medium.com/media/34ab070ba251a6749108b727a56df81d/href</a></iframe><p>Hopefully, this blog will enable you to optimize your framework and speed up testing. TestMu AI (formerly LambdaTest) is an AI-native software testing cloud for web, mobile, and AI applications. Its GenAI-native testing agent, KaneAI, plans tests and writes test cases and automation from natural language, tickets, or docs. You can run them on 3000+ browser and OS combinations and 10,000+ real Android and iOS devices, and orchestrate them at scale with HyperExecute. <a href="https://www.testmuai.com/selenium-automation/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun03_sd&amp;utm_term=rd&amp;utm_content=webpage">Run your existing Selenium, Cypress, Playwright, and Puppeteer tests</a> across 3000+ browser and OS combinations in parallel.</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84580cec010e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Detailed Guide On Selenium With Java [Tutorial]]]></title>
            <link>https://haritaravindranath.medium.com/a-detailed-guide-on-selenium-with-java-tutorial-ba7be94ccb85?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba7be94ccb85</guid>
            <category><![CDATA[selenium]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Thu, 02 Jun 2022 18:23:00 GMT</pubDate>
            <atom:updated>2026-10-21T09:22:32.426Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*wL6Im-0EGTzvjzeM5w03lw.jpeg" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/selenium-with-java/"><em>TestMu AI blog</em></a><em>.</em></p><p>While getting started with automation testing, two questions pop up in a tester’s mind.</p><ul><li>Which framework should be used for automation testing?</li><li>Which programming language should be preferred?</li></ul><p>When it comes to the <a href="https://www.testmuai.com/blog/best-test-automation-frameworks/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun02_sd&amp;utm_term=sd&amp;utm_content=blog">automation testing framework</a>, <strong>Selenium</strong> is often the first option that comes to our mind. Being open-source with large community support, Selenium has established itself as the favorite choice of automation testers over the last decade with significant traction.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2Fshr9sgvEpALrwPawH&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2Fshr9sgvEpALrwPawH&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c5edeef263b2e5e43524e7582a14f5d/href">https://medium.com/media/2c5edeef263b2e5e43524e7582a14f5d/href</a></iframe><p>When it comes to selecting the right programming language for writing tests, many factors have to be considered. This includes the language in which the Application Under Test (AUT) is being developed, community support, available test automation frameworks, IDE support, usability, simplicity, and the learning curve for the tester writing the test case.</p><p>Test scenarios in Selenium can be implemented in popular programming languages like C#, Java, JavaScript, Python, PHP, and Ruby. In this Selenium Java tutorial, let us explore the most popular combination in automation testing — Selenium with Java. By the end of this detailed guide, you will be in a position to kick start your journey in Selenium automation testing with Java. I have covered a range of topics like installation and project setup for writing your first test case. I will also cover some of the Selenium best practices for automation testing using Selenium with Java.</p><p>We have a lot to cover 🙂 So, let’s get started!</p><h3>Getting Started: Selenium Automation Testing with Java</h3><p>If you’re new to automation or moved from <a href="https://www.testmuai.com/blog/starting-automation-testing-from-scratch-here-is-what-you-need-to-know/">manual to automation testing</a>, then Selenium WebDriver is the best place to start. It has everything that you need to kickstart your Selenium automation journey.</p><p>In this section of this article on Selenium with Java, I will take you through the prerequisites and everything you need to know about Selenium to get started with Selenium automation testing with Java.</p><h3>What is Selenium?</h3><p>Selenium is a widely used automation testing framework used for browser automation of web applications. According to a recent test automation survey, 81% of the respondents used Selenium as their automating testing tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/0*LfDGw5__WXAMuydq.png" /><figcaption><a href="https://www.tricentis.com/state-of-open-source-2020/"><em>Source</em></a></figcaption></figure><p>A few features of Selenium that contributed to its popularity are</p><ul><li>Open-source with a large community.</li><li>Supports automation across multiple platforms like <strong>Windows, Macintosh, Linux</strong>, etc.,</li><li>Supports multiple browsers including <strong>Chrome, Firefox, IE, Safari</strong>, etc.</li><li>Supports multiple programming languages like <strong>Java, Python, Ruby, C#</strong>, etc.</li><li>Supports multiple frameworks like <strong>JUnit, TestNG</strong>, etc.</li><li>Easy to integrate with CI tools like <strong>Jenkins, Docker</strong>, etc.</li><li>Easy report generation</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*LCKwumNEAlMy4RMK.png" /></figure><p>Selenium is available in four different flavors, with the Selenium WebDriver being the most popular. Selenium WebDriver is an object-oriented API used for automating interactions with web browsers (e.g., Chrome, Firefox, Edge, etc.) using corresponding browser drivers.</p><p>We also have the Selenium Grid, which helps run tests in parallel across different browser and platform combinations. Selenium Grid follows a hub-node concept where we can run the WebDriver scripts on a single machine (hub), but the execution will be done by multiple remote machines (nodes) via routing commands.</p><p>TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/0*ULcr6tFaZXgnVjde.png" /></figure><p>The latest version, <strong>Selenium 4</strong>, comes with numerous major revamps, including enhanced architecture and advanced features. You can go through this Selenium 4 tutorial to learn <a href="https://www.testmuai.com/blog/what-is-deprecated-in-selenium4/">what is new in Selenium 4</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMmp_FiNIYtQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMmp_FiNIYtQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMmp_FiNIYtQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5795bfdf20160503416a809d730be858/href">https://medium.com/media/5795bfdf20160503416a809d730be858/href</a></iframe><p><strong><em>Do you know </em></strong>CSS Logical Properties<strong><em> and Values make it possible to control layout through logical, rather than physical, direction and dimension mappings. They are the writing-mode equivalent of their corresponding physical equivalents</em></strong>.</p><h3>How does Selenium WebDriver work?</h3><p>The Selenium WebDriver works with a <strong>Client-Server</strong> architecture model.</p><p>We have the <strong>Selenium Client Library on the client-side</strong>, which supports multiple client libraries corresponding to the programming language being used, like Java, Ruby, Python, etc. The language binding feature of Selenium allows it to support various programming languages. Based on the programming language of the test scripts, we need to choose the client library. For example, you need to use the Java language bindings to use Selenium with Java. You can download your respective language bindings from <a href="https://www.selenium.dev/downloads/">here</a>.</p><p>We have the <strong>Browser Driver on the server-side</strong>, which accepts the HTTP requests coming from the client-side via the communication protocol. The browser driver then interacts with the <strong>Real browser</strong> and drives it to execute the actions defined in the automation scripts. Every browser has a browser driver specific to it. For example, to automate the Chrome browser, you need to use the Chrome driver. Shown below are the locations from where you can download the respective browser driver.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrEc4J9rRwOcIob8&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrEc4J9rRwOcIob8&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a9546691f85a3455959620c994bd1a3/href">https://medium.com/media/9a9546691f85a3455959620c994bd1a3/href</a></iframe><p>The client-side and server-side interact with each other via a communication protocol.</p><p>For versions earlier than Selenium 4, the <strong>JSON wire protocol</strong> was used for communicating between the client and the server. It consists of the REST API that sends requests from the client to the server (browser’s native API) via HTTP. But here, since the Selenium Client Libraries (client) uses JSON protocol and the Web browser (server) users W3C protocol, encoding, and decoding of the API requests were required for communication between test scripts and browsers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SQclIkiqDyVq9yQP.png" /></figure><p>From Selenium 4, the JSON wire protocol is replaced by the WebDriver W3C protocol enabling direct communication between the Selenium Client libraries and the target browser. As the WebDriver and Web Browser use the same protocol, encoding and decoding of the API requests are no longer required making the test cases more stable than ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/0*CHwcmXsKA7AOKJtv.png" /></figure><h3>Why choose Selenium with Java?</h3><p>According to the <a href="https://insights.stackoverflow.com/survey/2021#technology">Stack Overflow Developer Survey</a>, Java is one of the most popular programming languages, preferred by more than 35% of the respondents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/0*UpP_GyrueT0mNRz2.png" /></figure><p>Choosing to write your Selenium automation tests using Java has multiple benefits. A few of them are listed below.</p><ul><li>As Selenium supports Java, detailed documentation is available, making it easy to write test cases.</li><li>Compared to other languages like Python, programs written in Java are faster.</li><li>Accessibility to various operating systems like UNIX, Linux, Windows, Mac OS, etc.</li><li>Java comes with multiple complete automation frameworks like TestNG, JUnit, etc., that can be leveraged with Selenium for better coding, reporting, and maintenance.</li></ul><h3>Installation and Setup: How to use Selenium with Java?</h3><p>To start your Selenium automation testing journey, the first step is to install and configure Selenium onto your system. In this section of this article on Selenium with Java, I will guide you through the installation process step by step. You will also be learning how to create a basic Selenium with Java project setup.</p><h3>Installation</h3><p>The installation process consists of the following steps.</p><ol><li>Install JDK.</li><li>Install Eclipse IDE.</li><li>Install Selenium WebDriver and Language Bindings.</li><li>Install Browser Drivers (Optional).</li></ol><h4>Install JDK</h4><p>Let us start with the Java Development Kit (JDK) installation. The JDK includes JRE (Java Runtime Environment) used to write and run Java code. You can download JDK from any of the below options.</p><ul><li><a href="https://www.oracle.com/java/technologies/downloads/">Oracle JDK</a></li><li><a href="https://www.openlogic.com/openjdk-downloads">OpenJDK</a></li></ul><p>Once the installation is complete, set the environment variables. The steps are as below:</p><ol><li>Right-click on Computer.</li><li>Click on ‘<strong>Properties</strong>’.</li><li>Click on ‘<strong>Advanced system settings</strong>’.</li><li>On System Properties, select the ‘<strong>Advanced</strong>’ Tab.</li><li>Click on ‘<strong>Environment Variables</strong>.’</li><li>Copy the path where the JDK is installed. (E.g.: C:\Program Files\Java\jdk1.6.0\bin )</li><li>In the opened <strong>Environment Variables</strong> window, select ‘<strong>New</strong>‘ under ‘<strong>System variables</strong>’.</li><li>Set the path. If ‘<strong>Path</strong>’ is already existing, then edit it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*6VU5_QNtD84CfUKdV8EWHA.png" /></figure><p>9. We also need to set the CLASSPATH. Create a new environment variable and copy the same JDK path as the value. If ‘CLASSPATH’ is already existing, then edit it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*Fe2ueZeG9IapRhoQ.png" /></figure><p>The environment variable setup is now complete.</p><p>Open the command prompt and run the following command to verify that Java has been successfully installed in your system.</p><pre>java -version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/0*VlVP-Rj92c0DILUN.png" /></figure><h4>Install Eclipse IDE</h4><p>Next, we need to install an IDE (Integrated Development Environment). An IDE is a platform where developers can write the code and run it. I will be using the <strong>Eclipse IDE for Java Developers</strong> for this demo. You can download the latest version from <a href="https://www.eclipse.org/downloads/">here</a>.</p><p>Once the installer file is downloaded, complete the installation process. Alternatively, you can also use any other popular IDE like Jetbrains Webstorm, IntelliJ IDEA, etc.</p><h4>Install Selenium WebDriver and Language Bindings</h4><p>Download the Selenium Client Library for Java from <a href="https://www.selenium.dev/downloads/">here</a>. The download comes as a ZIP file. Extract the contents (JAR files) and store them in a directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vwUD-yhWH8mWAmyq.png" /></figure><p>We are downloading client drivers for Selenium 4. Please check out ” <em>Previous Releases</em> ” for working with Selenium 3 or older versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZdPHag21yjDVDO4P.png" /></figure><h4>Install Browser Drivers (Optional)</h4><p>Finally, if you are running your test scripts on your local system, it is mandatory to have its respective browser driver for automating a browser. You can download the drivers for the browsers of your choice from <a href="https://www.selenium.dev/ecosystem/">here</a>.</p><p>However, if you are utilizing a cloud Selenium Grid like TestMu AI, you can skip this step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cG91NNsM5X0VOend.png" /></figure><p>With the installation process complete, let us move on to the project setup.</p><h3>How to create a Selenium Java project in Eclipse?</h3><p>We need to have a project set up for writing and storing our test cases. You can follow the below-mentioned steps to create a new Selenium with Java project in Eclipse.</p><p><strong>Step 1</strong>: Launch Eclipse<br><strong>Step 2</strong>: Create a workspace.</p><p>A workspace will be a place where you will be storing all your projects. You can create as many workspaces as required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/0*o7hujiwu4MLV5uA9.png" /></figure><p><strong>Step 3</strong>: Create a new Java project.</p><p>Go to <strong>File &gt; New &gt; Java Project</strong>. Name the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*n7Cloot977AzUrAW.png" /></figure><p>A new pop-up window will appear. Enter the following details:</p><ul><li>Project name</li><li>Location to save the project</li><li>Execution JRE</li></ul><p>Once done, click ‘<strong>Finish</strong>’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*cepp5fBVYt-L6vZS.png" /></figure><p>The project is now created.</p><p><strong>Step 4</strong>: Add Selenium API JAR files to the Java project by following the below-mentioned steps:</p><ol><li>Right-click on the project and select <strong>Properties</strong>.</li><li>Select <strong>Java Build Path</strong>.</li><li>Under the libraries section, click on <strong>Add External JARs</strong>, which gets enabled upon opting for Classpath.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NOZEdOY8zbpGIvK5.png" /></figure><p>4. Add the Selenium Java Client JARS. Navigate to the folder location where you have downloaded and extracted the JAR files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*TniRhPc2UohPRkRXnN2LfQ.png" /></figure><p>5. Once all the JAR files are added, click “<strong>Apply and Close</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1GEmOEoP7tNgH0BW6DI2A.png" /></figure><p>With our project configured with Selenium and Java, we are ready to write and run our first test script in Selenium.</p><p>If you’re a developer or a tester and want to take your Selenium with Java skills to the next level, this Selenium Java 101 certification from TestMu AI can help you reach that goal.</p><p>Here’s a short glimpse of the Selenium Java 101 certification from TestMu AI:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FvUxfvuAI7kE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DvUxfvuAI7kE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FvUxfvuAI7kE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/137b1a45c2e6efcd7834afedfaf60df1/href">https://medium.com/media/137b1a45c2e6efcd7834afedfaf60df1/href</a></iframe><p><strong><em>Check this out </em></strong>CSS Masks<strong><em>: you can mask part of an element using another element (or image)</em></strong></p><h3>[Demo] Writing the first test case using Selenium and Java</h3><p>It is time to hit practicals! In this section of this article on Selenium with Java, you will be learning to write your very first test case using Selenium with Java.</p><p><strong>Test Scenario</strong></p><p>First, let us understand the test scenario for which we will be writing a test script. We will be automating a simple form submission where the steps are as follows.</p><ol><li>Launch the website.</li><li>Enter the value for ‘<strong>a</strong>’.</li><li>Enter the value for ‘<strong>b</strong>’.</li><li>Click on the ‘<strong>Get Total</strong>’ button to display the sum of two numbers, ‘<strong>a</strong>’ and ‘<strong>b</strong>’.</li><li>Verify the result.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/0*dfzaXEWs_sRRvXpO.png" /></figure><h3>Case 1: Running our test case on a local machine</h3><p>In this section of this article on Selenium with Java, let us learn how to write the automated test case and run it on our local machine. The steps are detailed below.</p><p><strong>Step 1</strong>: Create a class file inside your Java Project.<br>Right-click on the <strong>src</strong> folder inside your Project. Select <strong>New &gt; Class</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/0*QU37aFF9qTZKKBtX.png" /></figure><p>I am naming it <strong>TestOne.java</strong>. The test gets created inside the default package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*bJ10YdTjAUh2R5Jh.png" /></figure><p><strong>Step 2</strong>: Write our test case code using Selenium with Java.</p><p>First of all, let us make the required Selenium imports on the top of our test class file. I will be running the test on the Chrome browser for this demo.</p><pre>import org.openqa.selenium.By;      <br>import org.openqa.selenium.WebDriver;              <br>import org.openqa.selenium.chrome.ChromeDriver;</pre><p>Inside the <strong>main()</strong> method, let us set properties to define the path of the browser driver, which we have downloaded during the installation steps.</p><pre>System.setProperty(“webdriver.chrome.driver”, “C:/location_of_chromedriver.exe”);</pre><p>After this, define a new Webdriver instance.</p><pre>WebDriver driver= new ChromeDriver();</pre><p>A glance of all possible methods WebDriver API provides us for browser automation is shown in the below snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*LRbHeaFTj0krPpWe.png" /></figure><p>Now, let us write the code for our test scenario.</p><pre>//Maximize window      <br>        driver.manage().window().maximize();    <br>       <br>        //Launch the Site.      <br>        driver.get(&quot;<a href="https://www.lambdatest.com/selenium-playground/simple-form-demo">https://www.lambdatest.com/selenium-playground/simple-form-demo</a>&quot;);<br>       <br>        //Enter values into form and submit      <br>        driver.findElement(By.id(&quot;sum1&quot;)).sendKeys(&quot;2&quot;);                    <br>        driver.findElement(By.id(&quot;sum2&quot;)).sendKeys(&quot;5&quot;);    <br>        driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=&#39;gettotal&#39;]/button&quot;)).click();  <br>       <br>        //Verify the result<br>        String result = driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=\&#39;addmessage\&#39;]&quot;)).getText();<br>       <br>        if( Integer.parseInt(result) == 7) {<br>             System.out.println(&quot;Test Success&quot;);<br>        } else {<br>             System.out.println(&quot;Test Failed&quot;);<br>        }<br>       <br>        //Close the browser<br>        driver.quit();</pre><p>I would like to briefly explain the WebDriver commands I have used in the test script.</p><ul><li>get(String arg): void</li></ul><p>The <strong>get()</strong> method takes a string URL as a parameter and opens the specified URL in the current browser window. This method returns nothing.</p><ul><li>findElement(By by): WebElement</li></ul><p>The findElement() method in Selenium is a WebElement command used to find a WebElement in the DOM for performing an action like clicking, typing, etc. It accepts an input parameter of the type <strong>By</strong> for locating the element using various locator strategies like id, classname, XPath, etc.</p><p>The <strong>findElement()</strong> returns a WebElement if the element is found, else throws a runtime exception — <strong>NoSuchElementException</strong>. To learn more about exception handling, you can go through this blog on common Selenium exceptions.</p><ul><li>quit(): void</li></ul><p>The <strong>quit()</strong> method is used to close all browser windows opened by the Webdriver. It accepts no parameter and returns nothing.</p><p>The WebElement methods used in the test script are:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrOB1zD3hIETGj9a&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrOB1zD3hIETGj9a&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbc0a0185c8a7368619d880752c5de30/href">https://medium.com/media/bbc0a0185c8a7368619d880752c5de30/href</a></iframe><p>To know more about the WebElement methods, please find the official documentation <a href="https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/WebElement.html">here</a>.</p><p>For locating the elements I made use of the browser <strong>Developer Tools</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4gLvsqS-POQomowX.png" /></figure><p>Our final code looks like this!</p><pre>import org.openqa.selenium.By;      <br>import org.openqa.selenium.WebDriver;              <br>import org.openqa.selenium.chrome.ChromeDriver;<br> <br>public class TestOne {<br> <br>    public static void main(String[] args) {<br>       <br>        System.setProperty(&quot;webdriver.chrome.driver&quot;, &quot;E:/Selenium/chromedriver.exe&quot;);<br>       <br>        WebDriver driver= new ChromeDriver();          <br> <br>        //Maximize window      <br>        driver.manage().window().maximize();    <br>       <br>        //Launch the Site.      <br>        driver.get(&quot;https://www.lambdatest.com/selenium-playground/simple-form-demo&quot;);<br>       <br>        //Enter values into form and submit      <br>        driver.findElement(By.id(&quot;sum1&quot;)).sendKeys(&quot;2&quot;);                    <br>        driver.findElement(By.id(&quot;sum2&quot;)).sendKeys(&quot;5&quot;);    <br>        driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=&#39;gettotal&#39;]/button&quot;)).click();  <br>       <br>        //Verify the result<br>        String result = driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=\&#39;addmessage\&#39;]&quot;)).getText();<br>       <br>        if( Integer.parseInt(result) == 7) {<br>             System.out.println(&quot;Test Success&quot;);<br>        } else {<br>             System.out.println(&quot;Test Failed&quot;);<br>        }<br>               //Close the browser<br>        driver.quit();              <br>    }<br>}</pre><p>Source: <a href="https://github.com/harita-R/selenium-java/blob/master/src/TestOne.java"><em>GitHub</em></a></p><p><strong>Step 3</strong>: Run the test.</p><p>Finally, it is time to run our test. Right-click on the test class file and select.</p><p><strong>Run As &gt; Java Application</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k_bQZqyz3na_QXUq.png" /></figure><p>The browser gets launched, and the test gets executed successfully on your local machine!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o63xIVdrrs2W3106.png" /></figure><p>You can also check the console for logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hp12bgii1HG1iaT8.png" /></figure><h3>Case 2: Running our test case on an online Selenium Grid</h3><p>In the previous section of this article on Selenium with Java, we have seen how to run our test case on a local machine. Here, let us explore how to run our test case in a remote cloud-based Selenium Grid.</p><p>Running our test cases in an online Selenium Grid helps us tackle the below-mentioned problems that occur during local execution when the project size and test coverage requirement increase.</p><ul><li>Scalability</li><li>Better browser coverage</li><li>Infrastructure limitations for cross browser testing etc.</li></ul><p>TestMu AI is a cross browser testing platform that provides an online browser farm of 3000+ browser and OS combinations and an online Selenium Grid that you can integrate with your current test project via minimum code changes. Follow along to learn how!</p><p>Here’s a glimpse of TestMu AI cloud Selenium Grid:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWZlsHlReRww%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWZlsHlReRww&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWZlsHlReRww%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/83eaa1ee47e2da460466c86ae2415011/href">https://medium.com/media/83eaa1ee47e2da460466c86ae2415011/href</a></iframe><p>You can also Subscribe to the TestMu AI<a href="https://www.youtube.com/channel/UCCymWVaTozpEng_ep0mdUyw?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun02_sd&amp;utm_term=sd&amp;utm_content=youtube"> YouTube Channel</a> and stay updated with the latest tutorials around Selenium testing, Cypress E2E testing, CI/CD, and more.</p><p><strong>Step 1</strong>: Create a free account on TestMu AI and secure your unique username and access key.</p><p><strong>Step 2</strong>: Inside the test class, define all the required variables for connecting with the Remote Grid. In addition, you can also define your unique username and access key.</p><pre>static String username = &quot;YOUR_USERNAME&quot;;<br>   static String accesskey = &quot;YOUR_ACCESS_KEY&quot;;<br>   static RemoteWebDriver driver = null;<br>   static String gridURL = &quot;<a href="http://twitter.com/hub">@hub</a>.lambdatest.com/wd/hub&quot;;<br>   static boolean status = false;</pre><p><strong>Step 3</strong>: Pass the browser capabilities. You can generate your custom desired capabilities using TestMu AI Capabilities Generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DR3DBgwn3LpJ02jB.png" /></figure><pre>DesiredCapabilities capabilities = new DesiredCapabilities();  <br>     capabilities.setCapability(&quot;browserName&quot;, &quot;Chrome&quot;);<br>     capabilities.setCapability(&quot;browserVersion&quot;, &quot;101.0&quot;);<br>     HashMap&lt;String, Object&gt; ltOptions = new HashMap&lt;String, Object&gt;();<br>     ltOptions.put(&quot;user&quot;,username);<br>     ltOptions.put(&quot;accessKey&quot;,accesskey);<br>     ltOptions.put(&quot;build&quot;, &quot;Selenium Java Test&quot;);<br>     ltOptions.put(&quot;name&quot;, &quot;TestOne&quot;);<br>     ltOptions.put(&quot;platformName&quot;, &quot;Windows 11&quot;);<br>     ltOptions.put(&quot;selenium_version&quot;,&quot;4.1.2&quot;);<br>     ltOptions.put(&quot;driver_version&quot;,&quot;101.0&quot;);<br>     capabilities.setCapability(&quot;LT:Options&quot;, ltOptions);</pre><p><strong>Step 4</strong>: Define a new instance of RemoteWebDriver()</p><p>Remote WebDriver is an interface which is used to execute the browser automation on a remote computing device or in a distributed environment. It can control the browser in the grid by configuring the node and the hub.</p><p>Note that you no longer need to pass the browser driver.</p><pre>try {<br>            driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>        }<br>        catch (MalformedURLException e) {<br>            System.out.println(&quot;Invalid grid URL&quot;);<br>        }<br>        catch (Exception e) {<br>            System.out.println(e.getMessage());<br>        }</pre><p><strong>Step 5</strong>: Our final code now looks like this!</p><pre>import java.net.MalformedURLException;<br>import java.net.URL;<br>import java.util.HashMap;<br> <br>import org.openqa.selenium.By;<br>import org.openqa.selenium.JavascriptExecutor;<br>import org.openqa.selenium.WebElement;<br>import org.openqa.selenium.remote.DesiredCapabilities;<br>import org.openqa.selenium.remote.RemoteWebDriver;<br> <br>public class TestOneWithRemoteGrid {<br>   <br>    static String username = &quot;YOUR_USERNAME&quot;;<br>    static String accesskey = &quot;YOUR_ACCESS_KEY&quot;;<br>    static RemoteWebDriver driver = null;<br>    static String gridURL = &quot;<a href="http://twitter.com/hub">@hub</a>.lambdatest.com/wd/hub&quot;;<br>    static boolean status = false;<br> <br>    public static void main(String[] args) {<br>       <br>        DesiredCapabilities capabilities = new DesiredCapabilities();<br>        capabilities.setCapability(&quot;browserName&quot;, &quot;Chrome&quot;);<br>        capabilities.setCapability(&quot;browserVersion&quot;, &quot;101.0&quot;);<br>        HashMap&lt;String, Object&gt; ltOptions = new HashMap&lt;String, Object&gt;();<br>        ltOptions.put(&quot;user&quot;,username);<br>        ltOptions.put(&quot;accessKey&quot;,accesskey);<br>        ltOptions.put(&quot;build&quot;, &quot;Selenium Java Test&quot;);<br>        ltOptions.put(&quot;name&quot;, &quot;TestOne&quot;);<br>        ltOptions.put(&quot;platformName&quot;, &quot;Windows 11&quot;);<br>        ltOptions.put(&quot;selenium_version&quot;,&quot;4.1.2&quot;);<br>        ltOptions.put(&quot;driver_version&quot;,&quot;101.0&quot;);<br>        capabilities.setCapability(&quot;LT:Options&quot;, ltOptions);<br>       <br>        try {<br>            driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>        } catch (MalformedURLException e) {<br>            System.out.println(&quot;Invalid grid URL&quot;);<br>        } catch (Exception e) {<br>            System.out.println(e.getMessage());<br>        }  <br>       <br>       <br>        //Maximize window      <br>        driver.manage().window().maximize();    <br>       <br>        //Launch the Site.      <br>        driver.get(&quot;<a href="https://www.lambdatest.com/selenium-playground/simple-form-demo">https://www.lambdatest.com/selenium-playground/simple-form-demo</a>&quot;);<br>       <br>        //Enter values into form and submit        <br>        driver.findElement(By.id(&quot;sum1&quot;)).sendKeys(&quot;2&quot;);                    <br>        driver.findElement(By.id(&quot;sum2&quot;)).sendKeys(&quot;5&quot;);    <br>        driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=&#39;gettotal&#39;]/button&quot;)).click();  <br>       <br>        //Verify the result<br>        String result = driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=\&#39;addmessage\&#39;]&quot;)).getText();<br>       <br>        if( Integer.parseInt(result) == 7) {<br>             System.out.println(&quot;Test Success&quot;);<br>        } else {<br>             System.out.println(&quot;Test Failed - &quot; + result);<br>        }                <br>       <br>        //Close browser<br>        driver.quit();                    <br>    }<br>}</pre><p>Source: <a href="https://github.com/harita-R/selenium-java/blob/master/src/TestOneWithRemoteGrid.java"><em>GitHub</em></a></p><p><strong>Step 6</strong>: Run the test.</p><p>The test starts running. Go to the TestMu AI Dashboard to observe the live running status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*baZvA7_TOvHVsIeG.png" /></figure><p>Our test got executed successfully. You can analyze the detailed report containing video and logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zt-R4ros2dfMI59R.png" /></figure><p>Moreover, you can navigate to the TestMu AI Analytics Dashboard to see test performance metrics. You can see the total number of tests passed or failed from the Test Summary section. You can also see the snapshot of consistent tests from the Test Overview section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*dRB_WYUv2VLDi3C7.gif" /></figure><p><strong><em>Do you know </em></strong>CSS math functions<strong><em> min(), max() and clamp() is a polyfill that provides more advanced mathematical expressions in addition to ‘calc()’</em></strong></p><h3>Using TestNG framework for parallel test execution</h3><p>If you are working on an actual project, you will need to write, run and maintain hundreds of test cases. Each testing cycle will demand you to execute your test cases on multiple platforms and devices to ensure that the application behaves as expected under various conditions to assure the product quality before going live. It becomes highly desirable to reduce the overall test execution time, and one way to achieve it is through parallel testing.</p><p><strong>Parallel testing</strong> is a favored test execution strategy where the tests are run in parallel to reduce overall test execution time. Parallel testing was introduced to replace the traditional approach of sequential testing. As the name suggests, tests are executed sequentially, which is more time-consuming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*OiBhAsUHm5YExMP-.png" /></figure><p>You have learned how to write and run a test case sequentially using Selenium with Java in the previous section. Now, I will walk you through how to run tests in parallel on a cloud-based Selenium Grid using the <strong>TestNG</strong> framework.</p><h3>Introduction to TestNG framework</h3><p>TestNG is a prominent open-source test automation framework for Java, where NG stands for ‘Next Generation.’ TestNG is widely adopted by Selenium users because of its features and feasibility. Running Selenium tests alone comes with numerous limitations. However, TestNG introduces an entire set of new features making it powerful and beneficial.</p><p>A few critical features of TestNG are listed below:</p><ul><li>Easy report generation in desirable formats. Now it is easier to analyze how many test cases passed and how many failed during each test run.</li><li>Supports parallel testing. Multiple test cases can be run simultaneously, reducing the overall test execution time.</li><li>Possible to group test cases in TestNG effortlessly.</li><li>TestNG annotations like @Test, @BeforeTest,@AfterTest, etc., are supported.</li><li>Easy to integrate with tools like Maven, Jenkins, etc.</li></ul><h3>Parallel test execution in TestNG using TestNG XML file</h3><p>As pointed out, one of the key advantages of adopting the TestNG automation framework is that it supports parallel test execution. TestNG test automation framework allows you to run tests in parallel or multithreaded mode by utilizing the Multi-Threading concept of Java.</p><p>Multi-Threading is the process of executing multiple threads simultaneously, without any dependence on each other. This means that the threads are executed in isolation, and therefore, exceptions occurring on one thread won’t affect the others. Multi-Threading helps in the efficient utilization of the CPU by greatly reducing idle time. In TestNG, we enable parallel testing by making required changes in the configuration file — <strong>TestNG XML</strong> file.</p><p>TestNG XML is the test suite configuration file in TestNG, which helps customize the execution of tests. It also allows you to run a single test file over numerous combinations of parameters and values specified. A simple TestNG XML file looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/0*4Fgew9ZKEjmGZ7hj.png" /></figure><p>To trigger parallel execution, we need to set the <strong>parallel</strong> attribute. This attribute accepts four values:</p><ul><li><strong>classes</strong> — to run all test cases present inside classes in the XML in parallel mode.</li><li><strong>methods</strong> — to run all methods with @Test annotation in parallel mode.</li><li><strong>tests</strong> — to run all test cases present inside tag in the XML in parallel mode.</li><li><strong>instances</strong> — to run all test cases in the same instance in parallel mode.</li></ul><p>We can also set the number of threads we wish to allocate during the execution using the <strong>thread-count</strong> attribute. The default value of thread count in TestNG is 5.</p><pre>&lt;suite name=”Regression Test Suite” parallel=”methods” thread-count=”2&quot;&gt;</pre><p>Moving forward, let us install and set up TestNG in our Eclipse. Also, let us learn how to rewrite our demo test case as a TestNG test and run it parallelly in three different browsers by leveraging the online Selenium Grid.</p><h3>Installation and Setup</h3><p>Installing TestNG in Eclipse is a simple process. Go to Eclipse Marketplace and install TestNG.</p><p><strong><em>Help &gt; Eclipse Marketplace.</em></strong></p><p>Once installed, you can locate it under the Installed section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/0*bxRSL58qaJN_TfUW.jpg" /></figure><p>With the installation completed, let us move on to a basic project setup next.</p><h3>Creating a TestNG Project</h3><p>To create a new Java TestNG project in Eclipse, follow the below-mentioned steps.</p><p><strong>Step 1</strong>: Launch Eclipse and create a new Java project.</p><p>Go to <strong><em>File &gt; New &gt; Java Project.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*kmndADmmicMq8uFk.png" /></figure><p><strong>Step 2:</strong> Name your project and click <strong>Next.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*FNeUd6fAYLeKoKDK.png" /></figure><p><strong>Step 3:</strong> Add libraries.</p><p>Right-click on the project folder and select Properties.</p><ol><li>Choose Java Build Path.</li><li>Go to Libraries, select Classpath, and click Add Library.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/0*l5AIO04XW0SC92cH.png" /></figure><p><strong>Step 4:</strong> Select TestNG and click Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*qy_CkYHWWLYwJ7Z6.png" /></figure><p>You will see that TestNG has been added to the project library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UpyXIG8ZCNfcKXvD.png" /></figure><p><strong>Step 5:</strong> Add the Selenium API JAR files to the TestNG project and click Apply and Close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JPJ3OkmJefRu-SkE.png" /></figure><p>We have successfully created a TestNG project and are ready to write and run our first TestNG test case.</p><h3>How to run test cases in parallel with Selenium in TestNG on Cloud Grid?</h3><p>In this section of this article on Selenium with Java, we will learn how to achieve parallel test execution in TestNG. For the demo, we will be re-writing our previous test case into a TestNG test and executing it parallelly on five different browsers (Chrome, Safari, Firefox, Opera, and Edge) using the Online Selenium Grid provided by TestMu AI.</p><p>The steps are detailed below.</p><p><strong>Step 1:</strong> Go to the TestNG project we created in the previous step.<br><strong>Step 2:</strong> Create a TestNG class file by following the below-mentioned steps:</p><ol><li>Right-click on project src and find TestNG towards the bottom of the list.</li><li>Select Create TestNG Class.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*XsMGMUrqZQJambIQ1I2OjQ.png" /></figure><p>3. Name the class, choose the required annotations, provide the XML file name and click Finish. Here, I have named the class as ParallelTest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*pelQ0RS9S__aYL_4a7fj4g.png" /></figure><p>The TestNG class file is created containing the skeleton code structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*-25LAygIdy3vUUpu.png" /></figure><p>Let us quickly go through the TestNG annotations used:</p><ul><li><strong>@Test</strong> — Implies that the method is a test case. Therefore, all tests should be marked with this annotation.</li><li><strong>@BeforeMethod</strong> and <strong>@AfterMethod</strong> — These annotations run once before and after each @Test method in a class.</li></ul><p><strong>Step 3:</strong> Write our test case using TestNG and Selenium.<br>I have re-written our previous test scenario as a TestNG test case. Some notable changes are:</p><ul><li>Inside the method marked by<strong> @BeforeMethod</strong> annotation, I have placed all the setup steps since they need to be executed first before the test. Also, the method name has been renamed <strong>setUp()</strong>. Additionally, a try-catch block has been implemented for exception handling.</li><li>Also, I have added <strong>@Parameters</strong> annotation on top of the method for receiving the browser, version, and platform values from our TestNG XML file.</li></ul><pre><a href="http://twitter.com/BeforeMethod">@BeforeMethod</a><br><a href="http://twitter.com/Parameters">@Parameters</a>(value={&quot;browser&quot;,&quot;version&quot;,&quot;platform&quot;})<br>public void setUp(String browser, String version, String platform) throws Exception {<br>        DesiredCapabilities capabilities = new DesiredCapabilities();<br>        capabilities.setCapability(&quot;browserName&quot;, browser);<br>        capabilities.setCapability(&quot;browserVersion&quot;,version);<br>        HashMap&lt;String, Object&gt; ltOptions = new HashMap&lt;String, Object&gt;();<br>        ltOptions.put(&quot;user&quot;,username);<br>        ltOptions.put(&quot;accessKey&quot;,accesskey);<br>        ltOptions.put(&quot;build&quot;, &quot;TestNG Parallel Test&quot;);<br>        ltOptions.put(&quot;name&quot;, &quot;TestOne&quot;);<br>        ltOptions.put(&quot;platformName&quot;, platform);<br> <br>        ltOptions.put(&quot;selenium_version&quot;,&quot;4.1.2&quot;);<br>        ltOptions.put(&quot;driver_version&quot;,&quot;101.0&quot;);<br>        capabilities.setCapability(&quot;LT:Options&quot;, ltOptions);<br> <br>     try {<br>         driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>     } catch (MalformedURLException e) {<br>         System.out.println(&quot;Invalid grid URL&quot;);<br>     } catch (Exception e) {<br>         System.out.println(e.getMessage());<br>     }<br> }</pre><ul><li>Inside the method marked by <strong>@AfterMethod</strong> annotation, I have placed the tear-down steps since they need to be executed last after every test. Also the method name has been renamed as <strong>tearDown()</strong>.</li></ul><pre><a href="http://twitter.com/AfterMethod">@AfterMethod</a><br>    public void tearDown() throws Exception {<br>       if (driver != null) {<br>            driver.quit();<br>        }<br>    }<br>}</pre><ul><li>We will be writing our actual code for test steps inside the method marked by<strong> @Test</strong> annotation. Since we are automating an additional scenario, I have renamed the method to addValues().</li></ul><pre><a href="http://twitter.com/Test">@Test</a><br>public void addValues() {<br>        //Maximize window      <br>        driver.manage().window().maximize();    <br>       <br>        //Launch the Site.        driver.get(&quot;<a href="https://www.lambdatest.com/selenium-playground/simple-form-demo">https://www.lambdatest.com/selenium-playground/simple-form-demo</a>&quot;);<br>       <br>        //Enter values into form and submit        <br>        driver.findElement(By.id(&quot;sum1&quot;)).sendKeys(&quot;2&quot;);                    <br>        driver.findElement(By.id(&quot;sum2&quot;)).sendKeys(&quot;5&quot;);    <br>        driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=&#39;gettotal&#39;]/button&quot;)).click();  <br>       <br>        //Verify the result<br>        String result = driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=\&#39;addmessage\&#39;]&quot;)).getText();<br>       <br>        if( Integer.parseInt(result) == 7) {<br>             System.out.println(&quot;Test Success&quot;);<br>        } else {<br>             System.out.println(&quot;Test Failed - &quot; + result);<br>        }<br></pre><p>The final code looks like this.</p><pre>g;<br> <br>import java.net.MalformedURLException;<br>import java.net.URL;<br> <br>import org.openqa.selenium.By;<br>import org.openqa.selenium.remote.DesiredCapabilities;<br>import org.openqa.selenium.remote.RemoteWebDriver;<br>import org.testng.annotations.AfterMethod;<br>import org.testng.annotations.BeforeMethod;<br>import org.testng.annotations.Parameters;<br>import org.testng.annotations.Test;<br> <br>public class ParallelTest {<br> <br>public String username = &quot;YOUR_USERNAME&quot;;<br>public String accesskey = &quot;YOUR_ACCESSKEY&quot;;<br>public RemoteWebDriver driver = null;<br>public String gridURL = &quot;<a href="http://twitter.com/hub">@hub</a>.lambdatest.com/wd/hub&quot;;<br>boolean status = false;<br> <br><a href="http://twitter.com/BeforeMethod">@BeforeMethod</a><br><a href="http://twitter.com/Parameters">@Parameters</a>(value={&quot;browser&quot;,&quot;version&quot;,&quot;platform&quot;})<br>public void setUp(String browser, String version, String platform) throws Exception {<br>        DesiredCapabilities capabilities = new DesiredCapabilities();<br>                capabilities.setCapability(&quot;browserName&quot;, browser);<br>        capabilities.setCapability(&quot;browserVersion&quot;,version);<br>        HashMap&lt;String, Object&gt; ltOptions = new HashMap&lt;String, Object&gt;();<br>        ltOptions.put(&quot;user&quot;,username);<br>        ltOptions.put(&quot;accessKey&quot;,accesskey);<br>        ltOptions.put(&quot;build&quot;, &quot;TestNG Parallel Test&quot;);<br>        ltOptions.put(&quot;name&quot;, &quot;TestOne&quot;);<br>        ltOptions.put(&quot;platformName&quot;, platform);<br>        ltOptions.put(&quot;selenium_version&quot;,&quot;4.1.2&quot;);<br>        ltOptions.put(&quot;driver_version&quot;,&quot;101.0&quot;);<br>        capabilities.setCapability(&quot;LT:Options&quot;, ltOptions);<br> <br>     try {<br>         driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>     } catch (MalformedURLException e) {<br>         System.out.println(&quot;Invalid grid URL&quot;);<br>     } catch (Exception e) {<br>         System.out.println(e.getMessage());<br>     }<br> }<br><a href="http://twitter.com/Test">@Test</a><br>public void addValues() {<br>        //Maximize window      <br>        driver.manage().window().maximize();    <br>       <br>        //Launch the Site.        driver.get(&quot;<a href="https://www.lambdatest.com/selenium-playground/simple-form-demo">https://www.lambdatest.com/selenium-playground/simple-form-demo</a>&quot;);<br>       <br>        //Enter values into form and submit        <br>        driver.findElement(By.id(&quot;sum1&quot;)).sendKeys(&quot;2&quot;);                    <br>        driver.findElement(By.id(&quot;sum2&quot;)).sendKeys(&quot;5&quot;);    <br>        driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=&#39;gettotal&#39;]/button&quot;)).click();  <br>       <br>        //Verify the result<br>        String result = driver.findElement(By.xpath(&quot;//*[<a href="http://twitter.com/id">@id</a>=\&#39;addmessage\&#39;]&quot;)).getText();<br>       <br>        if( Integer.parseInt(result) == 7) {<br>             System.out.println(&quot;Test Success&quot;);<br>        } else {<br>             System.out.println(&quot;Test Failed - &quot; + result);<br>        }   <br> <br><a href="http://twitter.com/AfterMethod">@AfterMethod</a><br>    public void tearDown() throws Exception {<br>       if (driver != null) {<br>            driver.quit();</pre><p><a href="https://github.com/harita-R/testng-parallel-tests/blob/master/src-tests/testng/ParallelTest.java">GitHub</a></p><p><strong>Step 4: </strong>Configure the TestNG XML file to run in parallel mode. The steps are as below:</p><ol><li>Open the testng.xml file. If not already created, you may create it by adding a new file to the project and naming it as testng.xml.</li><li>Edit the boilerplate. You can name the test suite and test name as per your liking. But the class name should be exact as that of our TestNG class.</li></ol><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE suite SYSTEM &quot;<a href="https://testng.org/testng-1.0.dtd">https://testng.org/testng-1.0.dtd</a>&quot;&gt;<br>&lt;suite name=&quot;Parallel Test Suite&quot;&gt;<br>    &lt;test name=&quot;Test&quot;&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt; &lt;!-- Test --&gt;<br>&lt;/suite&gt; &lt;!-- Suite --&gt;</pre><p>3. To trigger parallel test execution in TestNG, provide the parallel attribute to . For parallel execution of test methods, set the attribute value as “tests.”</p><pre>&lt;suite name=&quot;Parallel Test Suite&quot; parallel=&quot;tests&quot; thread-count=&quot;5&quot;&gt;</pre><p>4. Add parameters for configuring the tests to run in a specific browser, browser version, and OS. For example, below is the code for setting up the test case to run in Chrome Browser version 101.0 in Windows 11. Similarly, you can provide as many combinations as you like.</p><pre>&lt;test name=&quot;Chrome Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;Chrome&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;101.0&quot; /&gt;<br> <br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN11&quot; /&gt;<br> <br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;</pre><p>The final code for testng.xml looks like this.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;suite name=&quot;Suite&quot; parallel=&quot;tests&quot; thread-count=&quot;5&quot;&gt;<br> <br>    &lt;test name=&quot;Chrome Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;Chrome&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;101.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN11&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br> <br>    &lt;test name=&quot;Firefox Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;Firefox&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;100.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN8&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br> <br>    &lt;test name=&quot;Safari Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;safari&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;11.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;macos 10.13&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>   <br>    &lt;test name=&quot;MS Edge Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;Edge&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;101.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN10&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>   <br>    &lt;test name=&quot;Opera Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;Opera&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;85.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN10&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt; &lt;!-- Test --&gt;<br>&lt;/suite&gt; &lt;!-- Suite --&gt;</pre><p>We have a total of 5 different tags, and each of these will run on different threads.</p><p>5. Finally, it is time to run our test case. Right-click on our testng.xml file and navigate to <strong><em>Run As &gt; TestNG Test Suite</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCksfwnERNAKsMgYg4xoVQ.png" /></figure><p>Our test starts getting executed. Go to your TestMu AI<a href="https://accounts.lambdatest.com/login?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun02_sd&amp;utm_term=sd&amp;utm_content=it_sign_up"> Automation Dashboard</a> to see the live running status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*opHtFscoSmTxcyy9.png" /></figure><p>The test is executed parallelly in the 5 browsers, and reports and logs are generated successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ubReSkrbraVZZodd.png" /></figure><h3>Best Practices for Selenium automation testing</h3><p>Through automation testing, we aim to reduce the labor of manual testing, speed up the execution, detect maximum bugs early, achieve better coverage and accelerate time to market. However, writing a stable and reliant test case can be challenging due to various factors like test flakiness, incorrect testing approach, etc. This is where <a href="https://www.testmuai.com/blog/why-did-we-build-hyperexecute/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=jun02_sd&amp;utm_term=sd&amp;utm_content=blog">HyperExecute</a> comes into the picture, which eliminates these factors and cuts down on test execution times. This allows businesses to test code and fix issues much quicker and hence achieve an accelerated time to market.</p><p>In this section of this article on Selenium with Java, let us discuss some of the well-encouraged guidelines and design patterns recommended by the Selenium community to help you create well-architectured test suites. Remember, there is no “One Size Fits all” situation when it comes to test automation. Thoughtfully decide what will work the best for your particular environment.</p><ol><li><strong>Planning and Designing Test Cases beforehand</strong></li></ol><p>Before getting started with writing any automation tests, it is recommended that the QA teams invest time in creating a proper test plan. Surveys show that 80% of the projects dive straight into automation without having a tangible strategy.</p><p>However, to assure fool-proof testing of the application, QAs should come up with all possible logical scenarios and create maximum test cases based on the end-user perspective.</p><p><strong>2. Implementing Page Object Model</strong></p><p>When a UI change occurs, the Selenium locators may also change, and we are required to update the modified locators in all the test scripts consuming it. But, as the application complexity increases and UI changes become more frequent, creating and maintaining test cases becomes tiresome. The Page Object Model (POM) is a popular design pattern in Selenium automation testing, which helps in enhancing test maintenance and reducing code duplication.</p><p><strong>3. Choosing the Best-suited Locators</strong></p><p>While writing automation test scripts, a large chunk of the time is spent locating the web elements. Selenium offers us multiple strategies to locate a web element such as ID, Name, Link Text, XPath, CSS Selector, DOM Locator, etc.</p><p>However, some web locators are more brittle than others. As the UI implementation is prone to frequent changes, we must be cautious in choosing the right web locators, which will minimize the impact of UI code changes in the automation tests. If available, opt for unique locators like ID and Name, which are easy to find and more reliable as they are less prone to change.</p><p><strong>4. Implement Logging and Reporting</strong></p><p>As the test suite becomes extensive, locating the failed test case and debugging becomes challenging. In these cases, reporting and logging practices can act as huge saviors.</p><p>The test report is a document that contains all the information about a particular test run, including the number of test cases passed, the number of test cases failed, total time taken, error with a snapshot, etc. Even though default Selenium does not come with reporting, you can implement it by leveraging test automation frameworks like TestNG.</p><p>Logging helps us to understand our code better and hence makes debugging easier. Examining logs is the quickest way to analyze why your code faces a problem. Some of the popular log levels are debug, info, warning, error, and critical. Good logging saves time. However, if overdone, it can slow down test execution.</p><p><strong>5. Incorporating Wait Commands</strong></p><p>The web browsers take some time to load the web page contents. The time taken for page load depends on many external factors like network speed, server issues, machine capabilities, etc. To tackle this, testers need to add some delay into the code so that the web element will be loaded and available before performing any action on it.</p><p>In Java, testers often achieve this delay using Thread.sleep(). However, this is not the recommended practice. As the name implies, when the Thread.sleep() method is called, the thread goes to sleep for the specified amount of time and does absolutely nothing to pause the automation script. After the time is over, it moves on to executing the next line of code.</p><p>In real-time, we won’t be able to predict the exact time it would take for the page load as it is dependent on many external factors. Sometimes the page may load quickly, lowering the test execution speed due to the remaining unnecessary delay caused by sleep(). And sometimes, it may take longer than the specified time, causing the test to fail as the element was not fully loaded. As a better and more efficient alternative, use the <a href="https://www.selenium.dev/documentation/webdriver/waits/">Implicit wait and Explicit wait</a> commands provided by Selenium instead of the sleep method.</p><h3>Conclusion</h3><p>Selenium with Java is the most widely adopted test automation combination among QAs. In this tutorial, we explored how to get started with Selenium Automation Testing with Java and wrote our very first test case. On top of that, we also learned how to optimize test execution by leveraging parallel testing and other best practices to establish a reliable testing cycle. I hope this tutorial turns out to be beneficial. There’s much more to explore!</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba7be94ccb85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Perform Parallel Test Execution In TestNG With Selenium]]></title>
            <link>https://haritaravindranath.medium.com/how-to-perform-parallel-test-execution-in-testng-with-selenium-afb7cd91cb1d?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/afb7cd91cb1d</guid>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Thu, 21 Apr 2022 14:34:00 GMT</pubDate>
            <atom:updated>2026-10-21T09:20:04.968Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*y40LLNcWMaloCZ7KQhbqSQ.png" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/parallel-test-execution-in-testng/"><em>TestMu AI blog</em></a><em>.</em></p><p>The evolution in the process of software delivery in organizations in response to business agility has resulted in a paradigm shift from traditional release cycles to continuous release models. To achieve the product delivery objectives in this new paradigm, <a href="https://www.testmuai.com/blog/continuous-testing-using-shift-left-testing-approach/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr21_rd&amp;utm_term=rd&amp;utm_content=blog">continuous testing</a> plays a vital role in ensuring the quality of end-to-end processes, along with ensuring effective collaboration between Quality Assurance (QA) and development teams.</p><p>The new era of continuous testing demands QA teams to explore solutions to increase test execution speed. Enterprises are looking to leverage the benefits offered by automation testing while ensuring that manual testing is used in scenarios where automation is not possible.</p><p>The traditional approach of manual testing is already taken over by automation testing. One popular automation testing strategy widely adopted by QA teams to further reduce the testing time while ensuring maximum test coverage is the shift from sequential testing to <a href="https://www.testmuai.com/blog/what-is-parallel-testing-and-why-to-adopt-it/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr21_rd&amp;utm_term=rd&amp;utm_content=blog">parallel testing</a>. You can perform parallel test execution in TestNG or any other framework of your choice with Selenium.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*r9Py1hJ9r9tkdgeo9osJlw.gif" /></figure><p>In this <a href="https://www.testmuai.com/blog/create-testng-project-in-eclipse-run-selenium-test-script/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr21_rd&amp;utm_term=rd&amp;utm_content=blog">Selenium TestNG</a> tutorial, we deep dive into the integral aspects of parallel testing in TestNG.</p><p>Let’s get started!</p><h3>Introduction to Parallel Test Execution in TestNG</h3><p>Parallel testing is an approach in which independent tests are run parallel to reduce overall test execution time. A tester runs two or more versions of the software concurrently with the same input or test methods. Each test can be run on multiple devices, browsers, and OS combinations.</p><p>The parallel testing process can be applied to a single application, multiple applications, or even multiple components of an application. Parallel execution in TestNG can be achieved at different levels — threads, methods, etc.</p><p>Parallel testing was introduced to replace the traditional approach of sequential testing. As the name suggests, in sequential test execution tests are executed one after another, which is more time-consuming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*IdvudChXslX7lJV-yrVUug.jpeg" /></figure><p>Because of the growing demand for cross-browser testing in today’s market, parallel testing is implemented heavily with Selenium automation testing.</p><h3>Advantages of Parallel Test Execution in TestNG</h3><p>Parallel testing is a powerful approach that allows you to reduce the time taken to perform <a href="https://www.testmuai.com/automation-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr21_rd&amp;utm_term=rd&amp;utm_content=learning_hub">automation testing</a>. There are various reasons that make it important for testers to adopt parallel testing in Selenium. Some of the most popular reasons are:</p><ul><li><strong>Accelerated Test Execution Speed</strong></li></ul><p>If a sequential test takes 1 minute to complete a single test execution, it will take 5 minutes to run five tests one after another on the same device. However, overall test execution will take 1 minute (or less) when the same test is run in parallel on 5 devices (or input combinations).</p><ul><li><strong>Increased Test Coverage and Wider Compatibility</strong></li></ul><p>Parallel testing enables you to test across more devices (desktop or mobile), browsers, and OS combinations at once. This extended test coverage will help in risk mitigation, reducing the chance of unnoticed bugs and offering wider compatibility, which will be instrumental in shipping a top-quality product.</p><ul><li><strong>Overcome the Testing Bottleneck</strong></li></ul><p>Testing is often the bottleneck of DevOps. Tedious testing cycles can hold up the entire release process. But this bottleneck can be removed by accelerated test execution through parallel testing.</p><ul><li><strong>Fix Bugs Earlier</strong></li></ul><p>Earlier the testing is completed, earlier the bugs can be unearthed and fixed. In addition, parallel testing is results-driven, since we can test more scenarios in less time, and there is more actionable data towards enhancements.</p><ul><li><strong>Flexibility</strong></li></ul><p>You can revert to sequential testing when necessary.</p><h3>Challenges of Parallel Test Execution in TestNG</h3><p>To achieve full-fledged parallel testing, as with any type of testing, you may face some challenges. The common challenges that you will run into are often related to:</p><ul><li>Scalability</li><li>Infrastructure limitations. This includes:</li></ul><ol><li>Availability of secure, enterprise-grade lab that meet all the requirements</li></ol><p>2. Recurring investments involved in the maintenance and upgradation of test infrastructure.</p><p>The popular strategy recommended to overcome these challenges and move towards parallel testing is to use cloud-based testing providers. Through <a href="https://www.testmuai.com/blog/cloud-testing-tutorial/">Cloud testing</a>, teams can test their apps on devices and browsers hosted on the cloud infrastructure. By utilizing a cloud-based testing infrastructure, you no longer need to maintain in-house infrastructure.</p><p>Also, the scalability issues associated with the local testing infrastructure for covering all major browsers, their different versions, and OS will be taken care of. Needless to say, it is more cost-efficient as well.</p><p>TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications. You can choose a specific OS-device-browser combination as per your requirement. The platform also aids you in performing parallel testing in Selenium, which can drastically scale your automation test and reduce test execution time through easy setup and minimal configurations.</p><h3>How to perform Parallel Test Execution in TestNG?</h3><p>TestNG (where NG stands for ‘Next Generation’) is an open-source Java-based test automation framework that has gained huge popularity among developers and testers. The framework itself is inspired by JUnit, another popular unit testing framework in the Java ecosystem. However, it offers a variety of advanced and distinctive features, making it much more powerful than its peers. One such remarkable feature is the seamless support for Parallel Testing.</p><p>The TestNG <a href="https://www.testmuai.com/automation-testing/">test automation</a> framework allows you to run tests in parallel or multithreaded mode by utilizing the Multi-Threading concept of Java. Multi-Threading is the process of executing multiple threads simultaneously, without any dependence on each other. Therefore, exceptions occurring on one thread won’t affect the others. In TestNG, we enable parallel testing by making required changes in the configuration file — TestNG XML file.</p><p>With TestNG certification, you can challenge your skills in performing automated testing with TestNG and take your career to the next level.</p><p>Here’s a short glimpse of the TestNG certification from TestMu AI:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FdzXX2hJhuCY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DdzXX2hJhuCY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FdzXX2hJhuCY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c82719f7ccfbfef4357acc9912b3470/href">https://medium.com/media/6c82719f7ccfbfef4357acc9912b3470/href</a></iframe><p>However, you can follow the TestMu AI<a href="https://www.youtube.com/@TestMuAI"> YouTube Channel</a> and stay updated with the latest certifications and tutorials around Selenium testing, <a href="https://www.testmuai.com/cypress-testing/">Cypress testing</a>, and more.</p><h3>Parallel Test Execution in Selenium using Configuring TestNG XML in TestNG</h3><p>TestNG XML is the test suite configuration file in TestNG, which helps you organize your tests by defining test suites, grouping test cases in TestNG, and running them under one XML file. IN a nutshell, it helps in customizing the execution of tests.</p><p>It also allows you to run a single test file over numerous combinations of parameters and values specified in it. First, let us go through the key features of the TestNG XML file, which will be useful for this tutorial.</p><ul><li>Provides seamless parallel test execution</li><li>Supports <a href="https://www.testmuai.com/blog/parameterization-in-testng-dataprovider-and-testng-xml-examples/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr21_rd&amp;utm_term=rd&amp;utm_content=blog">parameterization in TestNG</a> using @Parameter annotation</li><li>Allows grouping of test methods and group execution</li><li>Allows executing test cases inside multiple Java class files</li><li>TestNG listeners automatically create logs</li></ul><p>A simple TestNG XML file without any configuration for the parallel tests will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*zAePnednW9YfAhEuOgvdig.png" /></figure><p>To trigger parallel test execution in TestNG, i.e., run tests on separate threads, we need to set the parallel attribute. This attribute accepts four values:</p><ul><li><strong>methods </strong>— runs all methods with @Test annotation in parallel mode</li><li><strong>tests</strong> — runs all test cases present inside &lt;test&gt; tag in the XML in parallel mode</li><li><strong>classes </strong>— runs all test cases present inside classes in the XML in parallel mode</li><li><strong>instances </strong>— runs all test cases in the same instance in parallel mode</li></ul><p>We can also set the number of threads we wish to allocate during the execution using the thread-count attribute. TestNG has a default value of thread = 5.</p><pre>&lt;suite name=&quot;Regression Test Suite&quot; parallel=&quot;methods&quot; thread-count=&quot;2&quot;&gt;</pre><p>Here, we have defined parallel test execution at suite level, and the @Test methods will start running simultaneously. The thread count is set to be 2, which means that only two threads will be created for this execution, on which 2 test methods will start running parallelly. If there are more than 2 methods, all the remaining ones need to wait until any of the threads get free.</p><p>Now that we know how to configure TestNG for running tests simultaneously, it’s time to do the hands-on! In the upcoming section of this Selenium TestNG tutorial, we will learn how to create a TestNG framework setup and write tests and execute them parallelly through the online Selenium Grid.</p><h3>Parallel Test Execution in multiple browsers using TestNG for Selenium automation testing</h3><p>In this section, we will be writing test cases in the TestNG framework and learning how to execute them parallelly at tests, classes, and methods levels by configuring the TestNG XML file. Our test cases will be executed on 5 different browsers — Chrome, Firefox, Safari, IE, and Opera by leveraging the online Selenium Grid provided by TestMu AI. Also, a custom configuration will be done for the browser as well as the OS version. Using TestMu AI, you can now test on Safari browser online on both desktop and mobile browsers for cross browser compatibility.</p><p>If you are already working with TestNG, feel free to skip the installation and project set-up part, which we will be covering next.</p><h3>Installation and Setup</h3><p>Before getting started with the project setup, make sure that your system is equipped with the following prerequisites:</p><ol><li><strong>Java<br></strong>TestNG requires JDK 8 or higher. If you do not have Java installed in your system, you can <a href="https://www.oracle.com/java/technologies/downloads/">download Java</a> from the Oracle official website. Don’t forget to set the environment variables as well.</li><li><strong>Eclipse IDE<br></strong>In this tutorial, for the demo, we will be using Eclipse as IDE. If not installed already, you can <a href="https://www.eclipse.org/downloads/">download Eclipse</a> from the official Eclipse website.</li><li><strong>Selenium Webdriver and Client for Java<br></strong>You can download by visiting the Selenium WebDriver <a href="https://www.selenium.dev/downloads/">official website</a>. Selenium WebDriver is an open-source, free Selenium testing tool for browser automation.</li></ol><p>Once this list is checked, the next step is to <a href="https://www.testmuai.com/blog/how-to-install-testng-in-eclipse-step-by-step-guide/">install TestNG in Eclipse</a>. First, go to Eclipse Marketplace and install TestNG. Once installed, you can locate it under the Installed section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*QXzwkFhqu5aFsif9uVohvA.jpeg" /></figure><p>You have now completed the installation. Let us do the basic project setup now.</p><p>Note: ClassList provides a way to manipulate classes using the DOMTokenList object.</p><h3>Creating a TestNG Project</h3><p>To use TestNG in a Java project, you must know how to create a TestNG project. You can follow the below-mentioned steps to create a new Java project in Eclipse.</p><p><strong>Step 1</strong>: Launch Eclipse and create a new Java project by navigating to <strong>File &gt; New &gt; Java Project</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*A0c2aAs3MXlaKywXlmC-gQ.png" /></figure><p><strong>Step 2</strong>: Name your project and click Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ukq-JRxrAU3Mjl0IuUIUsw.png" /></figure><p><strong>Step 3</strong>: Add libraries by following the below-mentioned steps:</p><ol><li>Right-click on the project folder and select Properties.</li><li>Choose Java Build Path.</li><li>Go to Libraries, select Classpath, and click Add Library.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*O-7VsSmGSQMMqokgagD7FQ.png" /></figure><p><strong>Step 4</strong>: Select TestNG and click Next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*BdsO2Fcot3XzNJdKFueM9g.png" /></figure><p><strong>Step 5</strong>: Now, you will see that TestNG is added to the project library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PsDIjRnlE2iCaB38e_UrkA.jpeg" /></figure><p><strong>Step 6</strong>: Click Finish, and we have successfully created a TestNG project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*8SeFI1c5loOefS0LZ29ePw.png" /></figure><p><strong>Step 7</strong>: Add Selenium API JAR files to the TestNG project by following the below-mentioned steps:</p><ol><li>Right-click on the project and select Properties.</li><li>Select Java Build Path.</li><li>Under the libraries section, click on Add External JARs, which gets enabled upon opting for Classpath.</li><li>Select the option and upload the JARs for Selenium Java language bindings by navigating to the path where you have downloaded and saved it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3XemaQjv9vlr3_t9kvLyJg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*lqyTA9VqPXYMnKRJ3fbQLQ.png" /></figure><p>5. Once done, select Apply and Close.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4aUXQO0BXrQhE2rAo0OBg.jpeg" /></figure><p>With this, our project set-up is done, and we are good to start coding. Notice that the libraries are also visible in the left panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*SljHI1EqOW8BTNQg4LaPgA.png" /></figure><p>Note: The Canvas API provides a way to generate fast, dynamic graphics using JavaScript.</p><h3>How to run test cases in parallel with Selenium in TestNG on Cloud Grid</h3><p>In this section, we will learn how to achieve parallel test execution in TestNG by running the test cases on separate threads. Follow the below mentioned steps:</p><p><strong>Step 1</strong>: Launch Eclipse and create a new Java project for TestNG. I have named it ParallelTestNG. You can skip this step if you have followed along with me in the Project set-up part.</p><p><strong>Step 2</strong>: Create a TestNG class file by following the below-mentioned steps:</p><ol><li>Right-click on project src and find TestNG towards the bottom of the list.</li><li>Select Create TestNG Class.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*Ksws22i4xusRUE2BoXhOBQ.png" /></figure><p>3. Name the class, choose the required annotations and click Finish. Here, I have named the class as TestCasesParallelExecution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*XAcnDhekOnvbL_ptPwRY-w.png" /></figure><p>Let us quickly go through the TestNG annotations that have been used:</p><ul><li><strong>@Test</strong> — Implies that the method is a test case. Therefore, all tests should be marked with this annotation.</li><li><strong>@BeforeMethod</strong> and <strong>@AfterMethod</strong> — These annotations run once before and after each @Test method in a class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*WB33X3CBWzv_MPAxLlTO0Q.png" /></figure><p><strong>Step 3</strong>: Write our first test case using TestNG and Selenium. Finally, it is time to get our hands dirty! In this section, we will be writing our first test case using TestNG. For this demo, I will be writing an automation test for a simple login scenario. Following are the test steps:</p><ol><li>Launch the website URL (<a href="https://opensource-demo.orangehrmlive.com/">https://opensource-demo.orangehrmlive.com/</a>)</li><li>Enter username and password.</li><li>Click on the LOGIN button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DNO_g0-xT1y7dQuMhGAr8A.png" /></figure><p>Like mentioned before, we will be running this test case parallelly on five different browsers through an online Selenium Grid provided by TestMu AI.</p><p>Let us write our test case inside the TestNG class we created in the previous step. Follow along with me.</p><p>1. Create a free account in TestMu AI and secure your unique username and access key.</p><p>2. Inside the ParallelTest class(the TestNG class), define all the required variables for connecting with the Remote Grid. In addition, you will need to provide your unique username, and access key.</p><pre>public class TestCasesParallelExecution {<br> <br>public String username = &quot;YOUR_USERNAME&quot;;<br>public String accesskey = &quot;YOUR_ACCESSKEY&quot;;<br>public RemoteWebDriver driver = null;<br>public String gridURL = &quot;<a href="http://twitter.com/hub">@hub</a>.lambdatest.com/wd/hub&quot;;<br>boolean status = false;<br>..<br>}</pre><p>3. Define automation setup steps inside the method marked by @BeforeClass annotation. This method gets executed first. Notice that I have also changed the method name from beforeClass() to setUp().</p><p>Inside the setUp(), we have defined the following:</p><ul><li><strong>DesiredCapabilities</strong> for custom configuring our browser-device-OS version, enabling reporting and logging features, and naming the build. I have generated this by utilizing the <a href="https://www.testmuai.com/capabilities-generator/">Desired Capabilities Generator</a> offered by TestMu AI.</li><li>A New instance of <strong>RemoteWebDriver()</strong></li><li>Also, I have added <strong>@Parameters</strong> annotation on top of the method for receiving the browser, version, and platform values from our TestNG XML file.</li></ul><pre><a href="http://twitter.com/BeforeMethod">@BeforeMethod</a><br><a href="http://twitter.com/Parameters">@Parameters</a>(value={&quot;browser&quot;,&quot;version&quot;,&quot;platform&quot;})<br>public void setUp(String browser, String version, String platform) throws Exception {<br>    DesiredCapabilities capabilities = new DesiredCapabilities();<br>     capabilities.setCapability(&quot;browserName&quot;, browser);<br>     capabilities.setCapability(&quot;version&quot;, version);<br>     capabilities.setCapability(&quot;platform&quot;, platform); // If this cap isn&#39;t specified, it will just get the any available one<br>     capabilities.setCapability(&quot;build&quot;, &quot;ParallelTestNG&quot;);<br>     capabilities.setCapability(&quot;name&quot;, &quot;ParallelTestNG&quot;);<br>     capabilities.setCapability(&quot;network&quot;, true); // To enable network logs<br>     capabilities.setCapability(&quot;visual&quot;, true); // To enable step by step screenshot<br>     capabilities.setCapability(&quot;video&quot;, true); // To enable video recording<br>     capabilities.setCapability(&quot;console&quot;, true); // To capture console logs<br>     try {<br>         driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>     } catch (MalformedURLException e) {<br>         System.out.println(&quot;Invalid grid URL&quot;);<br>     } catch (Exception e) {<br>         System.out.println(e.getMessage());<br>     }<br> }</pre><p>4. Define tear-down steps inside the method marked by @AfterClass annotation. This method gets executed last. Notice that I have also changed the method name from afterClass() to tearDown().</p><pre><a href="http://twitter.com/AfterMethod">@AfterMethod</a><br>    public void tearDown() throws Exception {<br>       if (driver != null) {<br>            driver.quit();<br>        }<br>    }</pre><p>5. Write our actual test steps. Our test methods will be marked by the @Test annotation. Since we are performing a login scenario, I have renamed the method to login().</p><pre><a href="http://twitter.com/Test">@Test</a><br>public void login() {<br>       <br>  // To navigate to URL<br>  driver.get(&quot;<a href="https://opensource-demo.orangehrmlive.com/">https://opensource-demo.orangehrmlive.com/</a>&quot;);<br>  // To locate input field for username and enter value<br>  driver.findElement(By.name(&quot;txtUsername&quot;)).sendKeys(&quot;Admin&quot;);<br>  // To locate input field for password and enter value<br>  driver.findElement(By.name(&quot;txtPassword&quot;)).sendKeys(&quot;admin123&quot;);<br>  // To locate and click on login button<br>   driver.findElement(By.className(&quot;button&quot;)).click();          <br>}</pre><p>I have made use of Chrome Developer tools for locating the elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MwxRa3zVsB6ryzRgm2FoIw.png" /></figure><p>Our final code looks like this:</p><pre>package testng;<br> <br>import java.net.MalformedURLException;<br>import java.net.URL;<br> <br>import org.openqa.selenium.By;<br>import org.openqa.selenium.remote.DesiredCapabilities;<br>import org.openqa.selenium.remote.RemoteWebDriver;<br>import org.testng.annotations.AfterMethod;<br>import org.testng.annotations.BeforeMethod;<br>import org.testng.annotations.Parameters;<br>import org.testng.annotations.Test;<br> <br>public class TestCasesParallelExecution {<br> <br>public String username = &quot;YOUR_USERNAME&quot;;<br>public String accesskey = &quot;YOUR_ACCESSKEY&quot;;<br>public RemoteWebDriver driver = null;<br>public String gridURL = &quot;@hub.lambdatest.com/wd/hub&quot;;<br>boolean status = false;<br> <br>@BeforeMethod<br>@Parameters(value={&quot;browser&quot;,&quot;version&quot;,&quot;platform&quot;})<br>public void setUp(String browser, String version, String platform) throws Exception {<br>    DesiredCapabilities capabilities = new DesiredCapabilities();<br>     capabilities.setCapability(&quot;browserName&quot;, browser);<br>     capabilities.setCapability(&quot;version&quot;, version);<br>     capabilities.setCapability(&quot;platform&quot;, platform); // If this cap isn&#39;t specified, it will just get the any available one<br>     capabilities.setCapability(&quot;build&quot;, &quot;ParallelTestNG&quot;);<br>     capabilities.setCapability(&quot;name&quot;, &quot;ParallelTestNG&quot;);<br>     capabilities.setCapability(&quot;network&quot;, true); // To enable network logs<br>     capabilities.setCapability(&quot;visual&quot;, true); // To enable step by step screenshot<br>     capabilities.setCapability(&quot;video&quot;, true); // To enable video recording<br>     capabilities.setCapability(&quot;console&quot;, true); // To capture console logs<br>     try {<br>         driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>     } catch (MalformedURLException e) {<br>         System.out.println(&quot;Invalid grid URL&quot;);<br>     } catch (Exception e) {<br>         System.out.println(e.getMessage());<br>     }<br> }<br>@Test<br>public void login() {<br>       <br>  // To navigate to URL<br>  driver.get(&quot;https://opensource-demo.orangehrmlive.com/&quot;);<br>  // To locate input field for username and enter value<br>  driver.findElement(By.name(&quot;txtUsername&quot;)).sendKeys(&quot;Admin&quot;);<br>  // To locate input field for password and enter value<br>  driver.findElement(By.name(&quot;txtPassword&quot;)).sendKeys(&quot;admin123&quot;);<br>  // To locate and click on login button<br>   driver.findElement(By.className(&quot;button&quot;)).click();          <br>}<br> <br>@AfterMethod<br>    public void tearDown() throws Exception {<br>       if (driver != null) {<br>            driver.quit();<br>        }<br>    }<br>}</pre><p><strong>Step 4</strong>: Configure the TestNG XML file. In this step, we will create the testng.xml file for our project and configure it to enable our tests to run in parallel mode. The steps are as below:</p><p>1. Right-click on our Project. Select New &gt; File and name it as testng.xml.</p><p>2. Add the following boilerplate code to get started. You can name the test suite and test name as per your liking. But the class name should be exact as that of our TestNG class.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE suite SYSTEM &quot;<a href="https://testng.org/testng-1.0.dtd">https://testng.org/testng-1.0.dtd</a>&quot;&gt;<br>&lt;suite name=&quot;Parallel Test Suite&quot;&gt;<br>    &lt;test name=&quot;Test&quot;&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt; &lt;!-- Test --&gt;<br>&lt;/suite&gt; &lt;!-- Suite --&gt;</pre><p>3. To trigger parallel test execution in TestNG, provide the parallel attribute to &lt;suite&gt;. As mentioned before, we can assign any of the four values given below, as per our requirement. For parallel execution of test methods, set the attribute value as “tests.”</p><pre>&lt;suite name=&quot;Parallel Test Suite&quot; parallel=&quot;methods&quot;&gt;</pre><p>4. Add parameters for configuring the tests to run in a specific browser, browser version, and OS. For example, below is the code for setting up the test case to run in Chrome Browser version 79.0 in Windows 10. Likewise, you can provide as many combinations as you like.</p><pre>&lt;test name=&quot;Chrome Test&quot; thread-count=&quot;3&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;chrome&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;79.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN10&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;</pre><p>The final code for testng.xml looks like this.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE suite SYSTEM &quot;https://testng.org/testng-1.0.dtd&quot;&gt;<br>&lt;suite name=&quot;Parallel Test Suite&quot; parallel=&quot;tests&quot; thread-count=&quot;5&quot;&gt;<br> <br>    &lt;test name=&quot;Chrome Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;chrome&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;79.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN10&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br> <br>    &lt;test name=&quot;Firefox Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;firefox&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;62.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN8&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br> <br>    &lt;test name=&quot;Safari Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;safari&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;11.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;macos 10.13&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>   <br>        &lt;test name=&quot;IE Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;ie&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;11.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN10&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>   <br>            &lt;test name=&quot;Opera Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;opera&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;73.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN10&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng.ParallelTest&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>   <br> <br>    &lt;!-- Test --&gt;<br>&lt;/suite&gt; &lt;!-- Suite --&gt;</pre><p>We have a total of 5 different tags, and each of these will run on different threads.</p><p>5. Finally, it is time to run our test case. Right-click on our testng.xml file and navigate to Run As &gt; TestNG Test Suite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*f11AnA__r2aXKiGiBs16pQ.png" /></figure><p>Our test starts getting executed. Go to your TestMu AI<a href="https://automation.lambdatest.com/timeline"> Automation Dashboard</a> to see the live running status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aASAJdV6K9QbQ5Tmqq-63g.png" /></figure><p>The test is executed parallelly in the 5 browsers, and reports and logs are generated successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4tKdU3oVq4MCRAxQbQrdWg.png" /></figure><h3>How to run test methods in parallel with TestNG</h3><p>Now let us see how to run test methods parallelly in the TestNG. In this example, we will create one more method and execute them on different threads. The steps are as below:</p><p><strong>Step 1</strong>: Create a new TestNG class file. You can also opt for an auto-defined TestNG XML file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*W9YWNuy-f4cz74eiaRXI2w.jpeg" /></figure><p><strong>Step 2</strong>: Inside this class, I have added a new test method forgotPassword() which will:</p><ol><li>Launch the website URL (<a href="https://opensource-demo.orangehrmlive.com/">https://opensource-demo.orangehrmlive.com/</a>).</li><li>Click on Forgot your password? link.</li><li>Enter Username.</li><li>Click the Reset Password button.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhIRMl2OquRZNV85LCkYpw.png" /></figure><pre><a href="http://twitter.com/Test">@Test</a><br>  public void forgotPassword() {<br> <br>    // To navigate to URL<br>    driver.get(&quot;<a href="https://opensource-demo.orangehrmlive.com/">https://opensource-demo.orangehrmlive.com/</a>&quot;);<br>    // To locate and click on Forgot password link<br>    driver.findElement(By.linkText(&quot;Forgot your password?&quot;)).click();<br>    // To locate input field and enter username<br>    driver.findElement(By.id(&quot;securityAuthentication_userName&quot;)).sendKeys(&quot;testuser&quot;);<br>    // To locate and click on reset button<br>    driver.findElement(By.id(&quot;btnSearchValues&quot;)).click();          <br>  }</pre><p>So the final code will look like this:</p><pre>package testng;<br>import java.net.MalformedURLException;<br>import java.net.URL;<br> <br>import org.openqa.selenium.By;<br>import org.openqa.selenium.remote.DesiredCapabilities;<br>import org.openqa.selenium.remote.RemoteWebDriver;<br>import org.testng.annotations.AfterMethod;<br>import org.testng.annotations.BeforeMethod;<br>import org.testng.annotations.Parameters;<br>import org.testng.annotations.Test;<br> <br>public class TestMethodParallelExecution {<br> <br>public String username = &quot;YOUR_USERNAME&quot;;<br>public String accesskey = &quot;YOUR_ACCESSKEY&quot;;<br>public RemoteWebDriver driver = null;<br>public String gridURL = &quot;@hub.lambdatest.com/wd/hub&quot;;<br>boolean status = false;<br> <br>@BeforeMethod<br>@Parameters(value={&quot;browser&quot;,&quot;version&quot;,&quot;platform&quot;})<br>public void setUp(String browser, String version, String platform) throws Exception {<br>    DesiredCapabilities capabilities = new DesiredCapabilities();<br>     capabilities.setCapability(&quot;browserName&quot;, browser);<br>     capabilities.setCapability(&quot;version&quot;, version);<br>     capabilities.setCapability(&quot;platform&quot;, platform); // If this cap isn&#39;t specified, it will just get the any available one<br>     capabilities.setCapability(&quot;build&quot;, &quot;TestMethodParallelExecution&quot;);<br>     capabilities.setCapability(&quot;name&quot;, &quot;TestMethodParallelExecution&quot;);<br>     capabilities.setCapability(&quot;network&quot;, true); // To enable network logs<br>     capabilities.setCapability(&quot;visual&quot;, true); // To enable step by step screenshot<br>     capabilities.setCapability(&quot;video&quot;, true); // To enable video recording<br>     capabilities.setCapability(&quot;console&quot;, true); // To capture console logs<br>     try {<br>         driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>     } catch (MalformedURLException e) {<br>         System.out.println(&quot;Invalid grid URL&quot;);<br>     } catch (Exception e) {<br>         System.out.println(e.getMessage());<br>     }<br> }<br> <br> <br>@Test<br>public void login() {<br>       <br>  // To navigate to URL<br>  driver.get(&quot;https://opensource-demo.orangehrmlive.com/&quot;);<br>  // To locate input field for username and enter value<br>  driver.findElement(By.name(&quot;txtUsername&quot;)).sendKeys(&quot;Admin&quot;);<br>  // To locate input field for password and enter value<br>  driver.findElement(By.name(&quot;txtPassword&quot;)).sendKeys(&quot;admin123&quot;);<br>  // To locate and click on login button<br>   driver.findElement(By.className(&quot;button&quot;)).click();          <br>}<br> <br>  @Test<br>  public void forgotPassword() {<br> <br>    // To navigate to URL<br>    driver.get(&quot;https://opensource-demo.orangehrmlive.com/&quot;);<br>    // To locate and click on Forgot password link<br>    driver.findElement(By.linkText(&quot;Forgot your password?&quot;)).click();<br>    // To locate input field and enter username<br>    driver.findElement(By.id(&quot;securityAuthentication_userName&quot;)).sendKeys(&quot;testuser&quot;);<br>    // To locate and click on reset button<br>    driver.findElement(By.id(&quot;btnSearchValues&quot;)).click();          <br>  }<br> <br>@AfterMethod<br>    public void tearDown() throws Exception {<br>       if (driver != null) {<br>            driver.quit();<br>        }<br>    }<br>}<br> <br>}</pre><p><strong>Step 3</strong>: Configure the TestNG XML file. Set the value of the parallel attribute as ”methods”. My testng2.xml file now looks like this.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE suite SYSTEM &quot;<a href="https://testng.org/testng-1.0.dtd">https://testng.org/testng-1.0.dtd</a>&quot;&gt;<br>&lt;suite name=&quot;Parallel Test Suite&quot; parallel=&quot;methods&quot; thread-count=&quot;2&quot;&gt;<br> <br>    &lt;test name=&quot;Chrome Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;chrome&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;79.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN10&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng2.TestMethodParallelExecution&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt;<br>    &lt;!-- Test --&gt;<br>&lt;/suite&gt; &lt;!-- Suite --&gt;</pre><p><strong>Step 4</strong>: Run the tests. Our two test methods start running in parallel. You can observe the live running status in your TestMu AI dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyX57X35RwYpOA2XQKhNtA.png" /></figure><p>Note: Autofocus attribute — a lightweight JavaScript library that allows a form field to be immediately focused on page load.</p><h3>How to run test classes in parallel with TestNG</h3><p>Lastly, let us see how to run test classes parallelly in the TestNG. First, let us create 2 classes that will be running parallel on separate threads.</p><p>1. Create 2 classes — TestClassOne and TestClassTwo. Each contains a test method.</p><p><strong>TestClassOne.java</strong></p><pre>package testng3;<br> <br>import org.testng.annotations.Test;<br>import org.testng.annotations.BeforeMethod;<br>import org.testng.annotations.Parameters;<br> <br>import java.net.MalformedURLException;<br>import java.net.URL;<br> <br>import org.openqa.selenium.By;<br>import org.openqa.selenium.remote.DesiredCapabilities;<br>import org.openqa.selenium.remote.RemoteWebDriver;<br>import org.testng.annotations.AfterMethod;<br> <br>public class TestClassOne {<br>   <br>    public String username = &quot;YOUR_USERNAME&quot;;<br>    public String accesskey = &quot;YOUR_ACCESSKEY&quot;;<br>    public RemoteWebDriver driver = null;<br>    public String gridURL = &quot;@hub.lambdatest.com/wd/hub&quot;;<br>    boolean status = false;<br> <br> <br>    @BeforeMethod<br>    @Parameters(value={&quot;browser&quot;,&quot;version&quot;,&quot;platform&quot;})<br>    public void setUp(String browser, String version, String platform) throws Exception {<br>        DesiredCapabilities capabilities = new DesiredCapabilities();<br>        capabilities.setCapability(&quot;browserName&quot;, browser);<br>        capabilities.setCapability(&quot;version&quot;, version);<br>        capabilities.setCapability(&quot;platform&quot;, platform); // If this cap isn&#39;t specified, it will just get the any available one<br>        capabilities.setCapability(&quot;build&quot;, &quot;TestMethodParallelExecution&quot;);<br>        capabilities.setCapability(&quot;name&quot;, &quot;TestMethodParallelExecution&quot;);<br>        capabilities.setCapability(&quot;network&quot;, true); // To enable network logs<br>        capabilities.setCapability(&quot;visual&quot;, true); // To enable step by step screenshot<br>        capabilities.setCapability(&quot;video&quot;, true); // To enable video recording<br>        capabilities.setCapability(&quot;console&quot;, true); // To capture console logs<br>        try {<br>            driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>        } catch (MalformedURLException e) {<br>            System.out.println(&quot;Invalid grid URL&quot;);<br>        } catch (Exception e) {<br>            System.out.println(e.getMessage());<br>        }<br>    }<br> <br>    @Test<br>    public void login() {<br> <br>        // To navigate to URL<br>        driver.get(&quot;https://opensource-demo.orangehrmlive.com/&quot;);<br>        // To locate input field for username and enter value<br>        driver.findElement(By.name(&quot;txtUsername&quot;)).sendKeys(&quot;Admin&quot;);  <br>        // To locate input field for password and enter value<br>        driver.findElement(By.name(&quot;txtPassword&quot;)).sendKeys(&quot;admin123&quot;);<br>        // To locate and click on login button<br>        driver.findElement(By.className(&quot;button&quot;)).click();            <br>    }<br> <br>    @AfterMethod<br>    public void tearDown() throws Exception {<br>        if (driver != null) {<br>            System.out.println(&quot;Tearing down..&quot;);<br>            driver.quit();<br>        }<br>    }<br>}</pre><p><strong>TestClassTwo.java</strong></p><pre>package testng3;<br> <br>import org.testng.annotations.Test;<br>import org.testng.annotations.BeforeMethod;<br>import org.testng.annotations.Parameters;<br> <br>import java.net.MalformedURLException;<br>import java.net.URL;<br> <br>import org.openqa.selenium.By;<br>import org.openqa.selenium.remote.DesiredCapabilities;<br>import org.openqa.selenium.remote.RemoteWebDriver;<br>import org.testng.annotations.AfterMethod;<br> <br>public class TestClassTwo {<br> <br>    public String username = &quot;haritagr16&quot;;<br>    public String accesskey = &quot;KhRUhWBtSMg06DfGkKDY1khYNJm95695WV42HfaYPot7nqQfw6&quot;;<br>    public RemoteWebDriver driver = null;<br>    public String gridURL = &quot;@hub.lambdatest.com/wd/hub&quot;;<br>    boolean status = false;<br> <br>    @BeforeMethod<br>    @Parameters(value={&quot;browser&quot;,&quot;version&quot;,&quot;platform&quot;})<br>    public void setUp(String browser, String version, String platform) throws Exception {<br>        DesiredCapabilities capabilities = new DesiredCapabilities();<br>        capabilities.setCapability(&quot;browserName&quot;, browser);<br>        capabilities.setCapability(&quot;version&quot;, version);<br>        capabilities.setCapability(&quot;platform&quot;, platform); // If this cap isn&#39;t specified, it will just get the any available one<br>        capabilities.setCapability(&quot;build&quot;, &quot;ParallelTestNG&quot;);<br>        capabilities.setCapability(&quot;name&quot;, &quot;ParallelTestNG&quot;);<br>        capabilities.setCapability(&quot;network&quot;, true); // To enable network logs<br>        capabilities.setCapability(&quot;visual&quot;, true); // To enable step by step screenshot<br>        capabilities.setCapability(&quot;video&quot;, true); // To enable video recording<br>        capabilities.setCapability(&quot;console&quot;, true); // To capture console logs<br>        try {<br>            driver = new RemoteWebDriver(new URL(&quot;https://&quot; + username + &quot;:&quot; + accesskey + gridURL), capabilities);<br>        } catch (MalformedURLException e) {<br>            System.out.println(&quot;Invalid grid URL&quot;);<br>        } catch (Exception e) {<br>            System.out.println(e.getMessage());<br>        }<br>    }<br>   <br>    @Test<br>    public void forgotPassword() {<br> <br>        // To navigate to URL<br>        driver.get(&quot;https://opensource-demo.orangehrmlive.com/&quot;);<br>        // To locate and click on Forgot password link<br>        driver.findElement(By.linkText(&quot;Forgot your password?&quot;)).click();  <br>        // To locate input field and enter username<br>        driver.findElement(By.id(&quot;securityAuthentication_userName&quot;)).sendKeys(&quot;testuser&quot;);<br>        // To locate and click on reset button<br>        driver.findElement(By.id(&quot;btnSearchValues&quot;)).click();              <br>    }<br> <br>    @AfterMethod<br>    public void tearDown() throws Exception {<br>        if (driver != null) {<br>            System.out.println(&quot;Tearing down..&quot;);<br>            driver.quit();<br>        }<br>    }<br>}</pre><p>2. Create a new TestNG XML file and set the parallel attribute as “classes.”</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE suite SYSTEM &quot;<a href="https://testng.org/testng-1.0.dtd">https://testng.org/testng-1.0.dtd</a>&quot;&gt;<br>&lt;suite name=&quot;Parallel Test Suite&quot; parallel=&quot;classes&quot; thread-count=&quot;2&quot;&gt;<br> <br>    &lt;test name=&quot;Chrome Test&quot;&gt;<br>        &lt;parameter name=&quot;browser&quot; value=&quot;chrome&quot; /&gt;<br>        &lt;parameter name=&quot;version&quot; value=&quot;79.0&quot; /&gt;<br>        &lt;parameter name=&quot;platform&quot; value=&quot;WIN10&quot; /&gt;<br>        &lt;classes&gt;<br>            &lt;class name=&quot;testng3.TestClassOne&quot; /&gt;<br>            &lt;class name=&quot;testng3.TestClassTwo&quot; /&gt;<br>        &lt;/classes&gt;<br>    &lt;/test&gt; <br>    &lt;!-- Test --&gt;<br>&lt;/suite&gt; &lt;!-- Suite --&gt;</pre><p>3. Run your test suite. The test gets executed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiQGm9i2eG0gdZpTokWGtA.png" /></figure><h3>Conclusion</h3><p>Parallel testing is widely adopted by Agile teams to radically reduce the time and cost associated with the traditional testing methods. It enables you to speed up the overall test cycle and deliver projects at a faster rate. To maximize the test coverage while ensuring scalability, the responsibility of maintaining a testing grid is often outsourced to cloud-based platforms.</p><p>In this Selenium TestNG tutorial, we learned how to achieve parallel test execution in the TestNG framework with Selenium. We have also leveraged the cloud-based Selenium Grid provided by TestMu AI to run our test cases parallelly in 5 different browsers while performing <a href="https://www.testmuai.com/selenium-automation-testing-with-testng/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr21_rd&amp;utm_term=rd&amp;utm_content=webpage">Selenium automation testing with TestNG</a>. I hope this tutorial turned out to be beneficial to you. So, keep exploring different angles of parallel testing.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afb7cd91cb1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Find Flaky Selenium Test Suite]]></title>
            <link>https://haritaravindranath.medium.com/how-to-find-flaky-selenium-test-suite-a1fd0f95e279?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1fd0f95e279</guid>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Fri, 08 Apr 2022 14:47:02 GMT</pubDate>
            <atom:updated>2026-10-21T09:11:30.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*n1dF0pfDWyvhRw1xRnkW5w.png" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/flaky-selenium-test-suite/"><em>TestMu AI blog</em></a><em>.</em></p><p>With Selenium being the most popular choice, automation testing has become an inevitable part of any Software Development Project. Backed by <a href="https://www.testmuai.com/blog/how-to-implement-continuous-testing-in-devops-like-a-pro/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr08_rd&amp;utm_term=rd&amp;utm_content=blog">Continuous Testing</a>, CI/CD pipelines, and DevOps, organizations make huge investments in setting up automatically triggered tests in the hopes of saving time, cost, and effort in the long run.</p><p>A well-planned and coded automation test will immensely aid in spotting bugs at an early stage of development. But there is a challenge that the Selenium Testers often encounter that can disrupt the entire productivity — <strong>Flaky Tests!</strong></p><p>What exactly does it mean to have a Flaky Selenium test suite? In this article on the Flaky Selenium test suite, we will discuss flaky tests, the common causes of a flaky Selenium test, how to isolate, find, and some practical tips to minimize them.</p><p>Let’s get started!</p><h3>What are Flaky Tests?</h3><p><strong>Determinism </strong>is the fundamental property of an automated test (or the entire Selenium test suite) that helps detect bugs. A test is deterministic if it always provides the same result, provided no change is introduced to the code. A flaky test is a test that passes or fails randomly for the same code, therefore, giving inconsistent results. One time it will pass, another time, it will fail, and next time pass again, without any change introduced to the build. Such a non-deterministic outcome defeats the primary purpose of <a href="https://www.testmuai.com/automation-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr08_rd&amp;utm_term=rd&amp;utm_content=webpage">automation testing</a>.</p><p>For example, consider the scenario of running a test suite in multiple browsers on a local machine. Then your test execution might be impacted by other processes, applications, or browser sessions running parallel in the background, competing for machine resources. In such cases, the test might fail on certain machines due to hardware limitations, even though there are no bugs in the application under test (AUT) itself.</p><p>The popular solution to overcome device limitations is switching from on-premises testing to cloud testing platforms. TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications.</p><h3>How common are Flaky Tests?</h3><p>Unfortunately, flaky tests are more common than you think.</p><p>A recent <a href="https://dl.acm.org/doi/fullHtml/10.1145/3476105">survey</a> of software developers found that 59% claimed to deal with flaky tests on a monthly, weekly, or daily basis.</p><p>After collecting a large sample of internal test results over one month, Google released a presentation, <a href="https://ai.google/research/pubs/pub45880">The State of Continuous Integration Testing @Google</a>, which uncovered some interesting insights.</p><ul><li>84% of the test transitions from Pass -&gt; Fail were from flaky tests</li><li>Only 1.23% of tests ever found a breakage</li><li>Almost 16% of their 4.2 million tests showed some level of flakiness</li><li>Flaky failures frequently block and delay releases</li><li>Between 2–16% of their compute resources were spent on re-running flaky tests.</li></ul><p>Google concluded that:</p><p><em>“Testing systems must be able to deal with a certain level of flakiness”</em></p><h3>Why are Flaky Tests bad?</h3><p>Flaky tests generate inconsistent results. They do not give a clear indication of the presence of software bugs and hence limit the reliability of the build. They are undesirable. But flaky tests can be worse than you think!</p><p>Some of the reasons are:</p><ul><li>Flaky tests can erode the overall trust in tests. It can encourage testers to overlook the test failures and dismiss actual defects by ignoring them as an outcome of test flakiness. This condition is called test results fatigue.</li><li>They affect the productivity of engineers with all the time taken to re-write, re-run and re-examine the tests. The false positives consume many resources that could be devoted to much more valuable work.</li><li>Flaky tests are expensive. They come with many hidden costs like creation, fixing, execution, fixing, business, and psychological costs.</li><li>As the test suite grows more extensive and is not timely maintained, so does the flakiness quotient. Since no one wants to deal with a large flaky test suite with untrustworthy results, testers might switch to manual testing. Now, this slows down the development process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*8Dz7F4drB4i7Zv0Dgvd69w.png" /></figure><p>Flaky tests can disrupt the development experience by slowing down the team’s progress and productivity. We all agree that it is frustrating to waste time re-running and debugging the code for potentially no bugs. In the upcoming section of this article on the Flaky Selenium test suite, let us take a deep dive into the common causes of flakiness in Selenium automation testing.</p><p>Note: <a href="https://www.testmuai.com/free-online-tools/url-parse/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr08_rd&amp;utm_term=rd&amp;utm_content=free_tools">URL Parse</a> functions focus on splitting a string into its components, or combining its components into a string.</p><h3>What causes a Flaky Selenium test suite?</h3><p>You might be wondering where exactly this flakiness is coming from? Is Selenium flaky as a tool? The answer is <strong>No. Selenium is not flaky. It is your test that is flaky.</strong> Let us understand the scene a bit.</p><p>The Selenium WebDriver language bindings are just a thin wrapper around the <a href="https://www.testmuai.com/blog/selenium4-w3c-webdriver-protocol/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr08_rd&amp;utm_term=rd&amp;utm_content=blog">W3C WebDriver Protocol</a> used to automate browsers. Selenium WebDriver implements a set of REST APIs exposed by the W3C Webdriver Protocol to perform relevant browser actions like starting the browser, clicking elements, typing input into fields, etc., as per the specifications.</p><p>The latest Selenium 4 introduces a major architectural update by W3C standardization of the Webdriver API and complete deprecation of the JSON wire protocol. The W3C protocol itself is deterministic hence implying Selenium WebDriver is deterministic as well. Major browser drivers like Geckodriver and Chromedriver have also completely adopted W3C protocols. In a nutshell, with Selenium 4, cross-browser tests are more reliable and efficient than ever!</p><p>So from where does the test flakiness come into the equation?</p><h3>Common causes of Flakiness in Selenium test suite</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*W2sMwZ75eBWfICMJ1XwEhg.jpeg" /></figure><p>The following are the key issues leading to a flaky test and corresponding solutions to acquire build stability:</p><ol><li><strong>Flaky Testing Environment</strong></li></ol><ul><li>Instability of the AUT environment.</li><li>Limitations of the machine where the test runs like processing speed, memory, etc.</li><li>Browser-related issues</li><li>Incorrect software versions used to run tests.</li><li>Unstable network connectivity, or slow connection,</li></ul><p><strong>2. Integration with Unreliable 3rd Party Tools and Applications</strong></p><ul><li>Third-party system errors</li><li>Third-party contract changes</li><li>Unreliable network connections</li></ul><p><strong>3. Lack of Synchronization</strong></p><ul><li>Page loading takes time due to front-end processing, loading heavy components, frames, content, etc.</li><li>Delayed response from API or database</li><li>Asynchronous processing</li><li>Not using correct “wait” strategies. The actual delay time depends on multiple external factors, and the test script may or may not pass depending on whether the delay given in the code was sufficient.</li></ul><p><strong>4. Poorly written tests</strong></p><ul><li>The test is large and contains a lot of logic.</li><li>The test depends on previous tests.</li><li>The test makes use of fixed waiting time.</li></ul><p><strong>5. Data Dependencies</strong></p><ul><li>No proper test data preparation</li><li>Hard coding of data</li><li>Using the same data in multiple tests may cause data corruption.</li><li>Corruption of data is caused by other colleagues who are using it and changing it.</li><li>User login to the portal.</li><li>User changes the password.</li></ul><p><strong>6. Locator strategy</strong></p><ul><li>Not taking care of dynamic elements effectively and using dynamic locators that vary based on the rendering of the AUT</li><li>Using weird, lengthy or hard-wired XPath.</li></ul><pre>/html/body/div[3]/div/div[4]/div/div/div/section/div/div/article/div/form/div/div[4]/div/label</pre><p><strong>7. Unintentional Invocation of Load Testing</strong></p><p>Sometimes, you introduce unnecessary complexity to your test framework, resulting in unexpected results. One such example is enabling parallel execution. As the test suite grows bigger, reducing overall test execution time through <a href="https://www.testmuai.com/blog/what-is-parallel-testing-and-why-to-adopt-it/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr08_rd&amp;utm_term=rd&amp;utm_content=blog">parallel testing</a> makes sense. But too many parallel test processes can amplify test flakiness.</p><p>One side effect of parallel tests is that they can introduce an unintentional load test by imposing large loads on the software it is not prepared for. For example, consider the case when all tests try to log in to the AUT during the test start using the same user credentials, and this implies multiple simultaneous logins happening to the same user. On the other hand, the tests may run fine during series execution in such cases.</p><p>8. <strong>Other reasons</strong></p><ul><li>Incorrect configuration of modules used in the frameworks</li><li>Using deprecated modules</li><li>Using incompatible tools for testing applications. (Eg: For Angular apps, Protractor would be a better choice than Selenium) etc.</li></ul><h3>How to find a Flaky Selenium Test and fix it?</h3><p>Now that you know the common reasons for flakiness introduced in your test suite let us explore how to locate a flaky selenium test and fix it.</p><p>Note: <a href="https://www.testmuai.com/free-online-tools/base64-encode/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr08_rd&amp;utm_term=rd&amp;utm_content=free_tools">Base64-encoding</a> or decoding is a simple way to protect or display your sensitive data.</p><h3>Common errors that appear when test fails due to Flakiness</h3><p>First of all let us check out some errors or exceptions often found when the test fails due to flakiness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uFaSKNvufeWIWNctV1L1Eg.png" /></figure><h3>Steps to fix a Flaky Selenium test suite</h3><p>You may not be able to eliminate flakiness in your Selenium test suite completely. However, you can minimize the flaky test’s impact and adverse effects by following the steps below.</p><ol><li><strong>Adopt the right design practices for your project</strong></li></ol><p>The first and most crucial step while getting started with automation testing is choosing the right test framework. A well-planned framework will not only relatively reduce the chance of flakiness but also will be easy to maintain and scalable.</p><p>Consider approaches like the <a href="https://www.testmuai.com/blog/selenium-java-testing-page-object-model/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr08_rd&amp;utm_term=rd&amp;utm_content=blog">Page Object Model</a> (POM) to make your framework robust and reusable. The POM is a commonly used design pattern in Selenium that creates an object repository for storing all web elements. The primary goal of this pattern is to avoid code duplication and enhance code reusability.</p><p>2. <strong>Write small and independent automated tests</strong></p><p>While writing automated tests, stick to the following principle:</p><ul><li>Each test should be small.</li><li>Each test should have only a single purpose to test one particular functionality.</li><li>Tests should be independent of each other.</li></ul><p>This helps in analyzing the cause of test failure efficiently. You can easily pick up any group of tests and run them in any order.</p><p>3. <strong>Identify and Isolate flaky tests</strong></p><p>The first step to fixing a flaky test is to identify them. Regularly run the test suite many times and spot the tests giving flaky results — preferably daily or at least weekly. One efficient way to do this is by using any CI service.</p><p>Implementing a CI service will aid you in running your whole test suite more often compared to running them on a local machine. If you want to detect the flaky tests in your suite, you should run them many times. Using CI testing, you can schedule your build to be run at different times in a day, and you might be able to discover some pattern of test failure. For e.g., A test is failing between 4–6 pm. It is ideal for implementing CI service at the beginning of the project itself.</p><p>After the analysis, you can separate your tests into two different paths: stable tests (green) and unstable flaky tests (red). You can set up your CI service to schedule a build regularly for the branch containing flaky tests to identify &amp; fix the issues. This way, you can easily divide attention between stable and unstable builds.</p><p>The goal is to make maximum tests green to prove that automation adds value.</p><p>4. <strong>Document Flaky Tests</strong></p><p>Documentation is part of the excellent testing practice. Once you have identified all the flaky tests in the suite, document them. One popular approach is creating tickets.</p><p>Add the information you have acquired about the cause of test flakiness to the ticket. By regularly running tests, you will be able to gather data like an average test run time, the number of times the test passed, the functionality being tested, etc. This will be a good place for tracking and discussing ideas to fix the test. Also, feel free to fix the tests right away where the cause of flakiness is obvious.</p><p>5. <strong>Determine the Cause of Failures</strong></p><p>It is now time to investigate why tests are going flaky. In some cases, the reason for test failure will be pretty straightforward, such as a bad locator, incorrect data, bad assertions, page load time, etc., and such cases can be closed quickly. But for the rest of the cases, you might need to dig deeper by gathering more information about the failure itself.</p><p>You can implement hooks that will fire when the test fails. Acquire data about the test failure like web page screenshots, error logs, application states, etc., which can aid in finding the culprit of flakiness. Analyze why the same tests are passing and failing intermittently.</p><p>6. <strong>Fix the flaky tests one at a time</strong></p><p>I recommend you work on fixing flaky tests one at a time. This will help you find the root cause of the failure, dissect the issue and provide a permanent fix. It can be tempting to take out as many tests as possible and fix them all in one go. But in reality, it would consume more time in the long run as it will be challenging to get to the root cause of failure and create a permanent fix.</p><p>You can debug the problem by commenting on code, monitoring logs, adding wait statements and breakpoints as needed, etc.</p><p>7. <strong>Add tests back to the stable test suite</strong></p><p>Once the test is fixed, ensure the test pass status is stable by running the test multiple times. If the results are satisfying, i.e., consistent successful runs, then add the test back to the stable test suite. It doesn’t end there! Re-run the stable test suite multiple times to make sure the build is stable.</p><h3>Tips to reduce Flakiness in a Selenium test suite</h3><p>Few essential strategies to eliminate flakiness and acquire build stability are:</p><ol><li><strong>Stabilize your test environment</strong></li></ol><p>As discussed, the unstable environment contributes to a flaky selenium test suite. Unsurprisingly it is common to overlook aspects like network latency, cache issues, server bugs, browser crashes, etc. In the blog post on Fix Your Unstable Automated UI Tests, Emanuil Slavov advocates that stabilizing his test environment helped increase the pass rate from 50% to 100%.</p><p>One popular solution to stabilize the test environment is to leverage cloud testing platforms. The primary benefits of cloud testing are:</p><ul><li>Cost-effectiveness</li><li>High-Performance</li><li>Faster test execution</li><li>Scalability</li><li>Customization</li></ul><p>TestMu AI provides you with a cloud-based <a href="https://www.testmuai.com/selenium-automation/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=apr08_rd&amp;utm_term=rd&amp;utm_content=webpage">Selenium Grid</a>, to run your Selenium automation scripts online enabling you to develop, test, and deliver faster every time by overcoming infrastructure limitations. Moreover, the grid is built on top of Selenium 4, bringing more efficiency and reliability to the automation code.</p><p><strong>2. Synchronous Wait</strong></p><p>Another sure-fire way to make your test result unstable is the incorrect usage of waits and sleeps. It is impossible to predict the exact time for a page load or for an asynchronous request to complete, which will trigger inconsistent results. To avoid flakiness in your script, you need to differentiate between implicit waits, explicit waits, and sleeping diligently.</p><p>According to <a href="https://speakerdeck.com/eviltester/your-automated-execution-does-not-have-to-be-flaky">Alan Richardson</a>, the synchronization issue is the top reason for automation failure and notes state-based synchronization is the solution to making it work.</p><p><strong>3. Usage of reliable Locators</strong></p><p>Another crucial practice is the usage of reliable locators. Choose locators that are unique, descriptive, and unlikely to change. Anything that doesn’t meet these criteria is a bad locator that will lead to testing failure.</p><p>The few best practices are:</p><ul><li>Always look for unique locators.</li><li>Make use of static IDs added by developers.</li><li>Dynamic IDs generated by web development frameworks change on every page load, rendering them useless. So, target only stable parts of dynamic IDs.</li><li>If you are working with XPath or CSS Selectors in Selenium, keep them short.</li></ul><h3>Conclusion</h3><p>Flaky tests are a living nightmare for automation testers. Flakiness gets introduced to your test suite for various reasons — an unstable environment, incorrect usage of async waits, bad locators, etc. Every tester deals with a flaky build from time to time, which is frustrating and time-consuming to debug.</p><p>In this article on the Flaky Selenium test suite, we discussed the flaky Selenium test suite, common reasons, and optimal approaches to find and fix the flakiness to boost the build stability by dissecting the root cause of test failure. Even if you cannot eliminate the flakiness from your test suite entirely, the measures we learned will assist you in minimizing it. Also, switching to the W3C compliant Selenium 4 will help you drastically reduce test randomness.</p><p>Hoping this article turned out to be beneficial.</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1fd0f95e279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Implement Drag And Drop In JavaScript Using Selenium?]]></title>
            <link>https://haritaravindranath.medium.com/how-to-implement-drag-and-drop-in-javascript-using-selenium-9e2b4ca5dbf0?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e2b4ca5dbf0</guid>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Tue, 29 Mar 2022 09:06:01 GMT</pubDate>
            <atom:updated>2026-10-21T09:15:24.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*3HCPhjY1AHl-k79otrZXIw.jpeg" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/how-to-implement-drag-and-drop-in-javascript/"><em>TestMu AI blog</em></a><em>.</em></p><p>Drag and Drop is an adored web feature implemented in many modern web applications. The list is endless, from cloud storage services like Google Drive and Dropbox to project management tools like Jira and Trello. As automation testers, it is our duty to leave no feature of our application untested. But often, it is tricky to automate a feature with complex user interaction like Drag and Drop.</p><p>Fortunately, the popular automation testing tool <a href="https://www.testmuai.com/blog/selenium-webdriver-tutorial-with-examples/?utm_source=medium&amp;utm_medium=Organic&amp;utm_campaign=mar_29&amp;utm_term=rd&amp;utm_content=Blog">Selenium WebDriver</a> offers functionality to easily automate dragging a web element from one part of the site and dropping it at another. In this article on how to implement drag and drop in JavaScript, we will learn how to write automation test code for the Drag and Drop feature using <a href="https://www.testmuai.com/blog/automation-testing-with-selenium-javascript/?utm_source=medium&amp;utm_medium=Organic&amp;utm_campaign=mar_29&amp;utm_term=rd&amp;utm_content=learning_hub">Selenium JavaScript</a>.</p><p>Let’s get started!</p><h3>What is Drag and Drop Action?</h3><p>Let us begin by understanding what exactly is the Drag and Drop operation in HTML.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4tyNAZ4Q7VX9CkgzKb-mA.gif" /></figure><p>The drag and drop action is a GUI-based software feature done with the help of a mouse. This feature enables us to “hold” an element, “drag” it to a different location or onto another virtual object and “drop” it to the target location. In HTML, any element can be dragged and dropped.</p><p>The workflow of a typical drag and drop feature is as follows:</p><ol><li>The element of interest, which is to be dragged and dropped, must be visible on the screen.</li><li>The user initiates interaction by acquiring the item. The selection technique can be a mouse click.</li><li>Keeping the item selected, the user moves the pointing device (mouse) to the desired location or target through continuous press or “drag.”</li><li>Once the desired location or target is reached, the user lets go of the item, and it is now “dropped.”</li></ol><p>Drag and Drop is a part of many user interfaces we use every day. Some common examples are:</p><ul><li>Uploading a file to a web application (Eg: Google Drive)</li><li>Moving a file from one folder to another (Eg: Gmail )</li><li>Reordering, Resizing, and Grouping of objects (Eg: JIRA, Trello)</li><li>Rearranging browser tabs (Eg: Chrome, Firefox)</li></ul><h3>How to implement Drag and Drop in JavaScript?</h3><p>We can automate the Drag and Drop operation by leveraging the <a href="https://www.testmuai.com/blog/what-is-actions-class-in-selenium/?utm_source=medium&amp;utm_medium=Organic&amp;utm_campaign=mar_29&amp;utm_term=rd&amp;utm_content=Blog">Actions class in Selenium</a> provided by the Selenium WebDriver API. The actions class supports two methods, using which we can drag and drop an element. They are</p><ul><li>dragAndDrop method</li><li>dragAndDropBy method</li></ul><p>In addition to these two methods, we can also make use of the following Actions class method to achieve drag and drop automation. They are:</p><ul><li>moveByOffset method</li><li>moveToElement method</li></ul><p>Before we get deeper into how to implement drag and drop in JavaScript, let us understand more about the Actions class itself.</p><h3>What is the Actions class in Selenium?</h3><p>The <strong>WebElement commands</strong> need no introduction, and they help us identify a WebElement and perform various actions on it. Most basic user interactions like clicking on a button or entering text to an input field can be achieved using the WebElement commands.</p><p>Some popular commands are:</p><ul><li><strong>WebElement.click()</strong> — to click on a web element</li><li><strong>WebElement.sendKeys()</strong> — to enter text to a field</li><li><strong>WebElement.submit()</strong> — to submit a form etc.</li></ul><p>However, if you need to perform complex interactions like Drag and Drop Double-click, or Click and Hold an element, they cannot be achieved using simple WebElement commands alone. And this is where the <strong>Actions class</strong> comes into the picture.</p><p>The official documentation describes the Actions class as:</p><p><em>“The user-facing API for emulating complex user gestures. Use this class rather than using the Keyboard or Mouse directly.”</em></p><p>In short, to automate advanced keyboard-based or mouse-based actions in Selenium, you need to utilize the Actions class in Selenium. The methods within the Actions class can be divided into two main categories:</p><ul><li><strong>Keyboard Events</strong> — keyDown(), keyUp(),sendKeys(), etc.</li><li><strong>Mouse Events</strong> — dragAndDrop(), dragAndDropBy(), moveByOffset(), moveToElement() etc.</li></ul><p>The various actions supported by the actions class are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*fiDD-PvhGbJiDokffBPkow.gif" /></figure><h3>Syntax for Drag and Drop in Selenium</h3><p>At the beginning of this section on JavaScript drag and drop, we learned that the Actions class supports two methods that enable the automation of the drag and drop action. Now, let us study them in detail, along with the syntax required to perform the action.</p><ol><li><strong>dragAndDrop method</strong></li></ol><p>This method is used to perform a Drag and Drop operation where you need to left-click on an element, hold it and drag it to the desired target location and drop it.</p><p><strong>Syntax:</strong></p><pre>Actions.dragAndDrop(WebElement source, WebElement target)</pre><p>This method accepts two parameters:</p><ul><li><strong>source </strong>— the web element which we need to click and start the drag</li><li><strong>target</strong> — the web element on which we need to drop the source element</li></ul><p>To find the source and target element, we can use any locator strategy.</p><pre>driver.findElement(Any By strategy &amp; locator)</pre><p><strong>2. dragAndDropBy method</strong></p><p>This method is used to perform Drag and Drop operations in Selenium using x and y offsets. The source element will be dragged and dropped at the location specified via the x-axis and y-axis offsets in pixels.</p><pre>Actions.dragAndDropBy(WebElement source, int xOffset, int yOffset)</pre><p>This method accepts three parameters:</p><ul><li><strong>source </strong>— the element which we need to click and start the drag</li><li><strong>xOffset</strong> — x-axis pixel value which defines the horizontal movement of the source element</li><li><strong>yOffset </strong>— y-axis pixel value which defines the vertical movement of the source element</li></ul><p>Again, to find the source element, we can use any locator strategy.</p><pre>driver.findElement(Any By strategy &amp; locator)</pre><p>The dragAndDropBy() works similar to the dragAndDropBy(), but the only difference is that dragAndDropBy() moves the source element to the offsets and not to any target element.</p><p>Finally, once the dragAndDrop() or dragAndDropBy() method is defined with parameters, the <strong>perform()</strong> method needs to be invoked for performing the action.</p><pre>Actions.dragAndDrop(WebElement source, WebElement target).perform();</pre><p>OR</p><pre>Actions.dragAndDropBy(WebElement source, int xOffset, int yOffset).perform();</pre><p>Alternatively, we can also achieve drag and drop automation by <strong><em>clicking and holding</em></strong> an element, <strong><em>moving </em></strong>it to the target position, and then <strong><em>releasing </em></strong>it. To execute this operation sequence, we will be making use of the following methods from the Actions class.</p><ul><li>clicking and holding a web element via <strong>clickAndHold()</strong></li><li>moving to the target location via <strong>moveToElement()</strong> or <strong>moveByOffset()</strong></li><li>release mouse button at target position via <strong>release()</strong></li></ul><p>Let us check out them in detail, along with the syntax below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*XLc38F-NMdyFd6rpA4V9QA.png" /></figure><p><strong>3. moveToElement method</strong></p><p>This method is used to move the mouse to a specified web element. We can also move a draggable web element using this method.</p><p><strong>Syntax:</strong></p><pre>Actions.clickAndHold(WebElement source).moveToElement(WebElement target).release().perform();</pre><ul><li>The web element which we desire to click and hold is passed to the clickAndHold()</li><li>Then, we move the mouse pointer to the target web element specified within in moveToElement()</li><li>Then, we release the element from the mouse button hold using release().</li><li>Finally, we invoke the perform() for performing this chain of actions currently built.</li></ul><p><strong>4. moveByOffset method</strong></p><p>This method is used to move the mouse to the specified offset of the last known mouse coordinates. On the initial page load, the mouse coordinates will be (0,0). We can also move a draggable web element using this method.</p><p><strong>Syntax:</strong></p><pre>Actions.clickAndHold(WebElement source).moveByOffset(int xOffset,int yOffset).release().perform();</pre><ul><li>The web element which we need to click and hold is passed to the <strong>clickAndHold()</strong></li><li>Then, we move the mouse pointer to the target location by passing the X and Y offsets within in <strong>moveByOffset()</strong></li><li>Then, we release the element from the mouse button hold using <strong>release()</strong>.</li><li>Finally, we invoke the <strong>perform()</strong> for performing this chain of actions currently built.</li></ul><p>Note: With the help of Import maps, you can control what URLs get fetched by JavaScript’s `import` statements and `import()` expressions.</p><h3>Syntax for Drag and Drop in JavaScript using Selenium</h3><p>To work with Selenium using JavaScript drag and drop, we will be making the <strong>selenium-webdriver</strong> library. Here, the syntax for calling <strong>Actions class</strong> and the available methods are slightly different. To use the JavaScript drag and drop feature in Selenium automation testing, we will be utilizing the <strong>dragAndDrop</strong> method.</p><ol><li><strong>dragAndDrop method</strong></li></ol><p>This method helps us to configure drag and drop action by passing either the target web element or X and Y offsets.</p><p><strong>Syntax:</strong></p><pre>this.dragAndDrop(WebElement from, WebElement|{x: number, y: number} to ).perform();</pre><p>The function accepts two parameters:</p><ul><li><strong>from</strong> — the web element which we need to click and start the drag</li><li><strong>to </strong>— either a web element or offset (in pixel) to mark the target location where the element needs to be dropped.</li></ul><p>In the next section of this article on how to implement drag and drop in JavaScript, we will demonstrate writing a test case to automate Drag and Drop in JavaScript using Selenium.</p><h3>How to write a test case to automate Drag and Drop in JavaScript using Selenium</h3><p>So far, we have discussed the Actions class and various methods to automate the Drag and Drop feature. Finally, it’s time to get your hands dirty!</p><p>In this section of how to implement drag and drop in JavaScript, you will be learning how to drag and drop using JavaScript while performing <a href="https://www.testmuai.com/selenium-automation/?utm_source=medium&amp;utm_medium=Organic&amp;utm_campaign=mar_29&amp;utm_term=rd&amp;utm_content=webpage">Selenium test automation</a>.</p><h3>Prerequisites</h3><p>I am assuming that the following prerequisites are installed in your system.</p><ul><li>Node.js and NPM</li><li>Visual Studio Code or any IDE of choice</li></ul><p>Note: Intl.PluralRules API<strong> -</strong>API for plural language rules and plural sensitive formatting.</p><h3>Test Scenario</h3><p>For this demo, I will be writing the test case for the following simple and straightforward scenario.</p><ol><li>Launch the browser.</li><li>Go to the Selenium Playground website.</li><li>Perform Drag and Drop by selecting the first element and dragging and dropping it on the second element.</li><li>Close the browser.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*bedtkpBPHB2Dmxzai9IkAA.gif" /></figure><p>I will be executing the test case on three different browsers — Firefox, Chrome, and Safari — using the online Selenium Grid provided by TestMu AI. TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications. On top of that, TestMu AI also supports web testing in the latest Selenium 4.</p><h3>Steps for Writing the Drag and Drop test case</h3><p>Now, it’s time to write tests in Selenium WebDriver for automation testing. From project set-up to test execution, I will be walking you through the whole process step by step.</p><ol><li><strong>Using dragAndDrop() by passing source and target web elements</strong></li></ol><p><strong>Step 1:</strong> Create a new folder for your project. Open the folder location via your IDE (Visual Studio Code) and initialize the project by giving the following command in the terminal.</p><pre>npm init -y</pre><p>The project is now initialized, and the <strong>package.json</strong> file is created in the root folder.</p><p><strong>Step 2:</strong> Install dependencies</p><pre>npm install selenium-webdriver</pre><p><strong>Step 3: </strong>Create a folder named “<strong>tests</strong>” within your project root folder. We will be storing all our test cases here. Inside this folder, create your first test case file, “<strong>test.js</strong>.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*Yu8gasTIoquU2eU5dDEFPw.png" /></figure><p><strong>Step 4:</strong> Inside the test.js file, add required imports and configurations to run the test on a cloud grid hosted by TestMu AI.</p><ol><li>Create a free account in TestMu AI and fetch your unique username and access key.</li><li>Define the username and access key in your test.js file. Also, define the grid host.</li></ol><pre>const USERNAME = &quot;YOUR_USERNAME&quot;; //replace with your username<br>const KEY = &quot;YOUR_ACCESSKEY&quot;; //replace with your access key</pre><pre>const GRID_HOST = &quot;hub.lambdatest.com/wd/hub&quot;;<br>const gridUrl = &quot;https://&quot; + USERNAME + &quot;:&quot; + KEY + &quot;@&quot; + GRID_HOST;</pre><p>3. Make the required imports.</p><pre>const { Builder, Key, By } = require(&quot;selenium-webdriver&quot;);</pre><p><strong>Step 5:</strong> Define the test method. Create a function <strong>example()</strong>, which will be containing your test script. Feel free to provide any function name of your choice.</p><pre>async function example() {<br>}</pre><p>At the beginning of this test method, let us define the required capabilities. To generate your custom desired capability to meet your browser and OS version requirement, make use of the TestMu AI Capabilities Generator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqfbJi0Y8FKmTf6NBGQERg.png" /></figure><p>Here I have set the capability to run my test case in Chrome browser version 91.0 in the windows 10 platform using Selenium 4.</p><pre>var capabilities = {<br>      build: &quot;Drag and Drop&quot;,<br>      name: &quot;Drag and Drop&quot;,<br>      platform: &quot;Windows 10&quot;,<br>      browserName: &quot;Chrome&quot;,<br>      version: &quot;91.0&quot;,<br>      selenium_version: &quot;4.0.0&quot;,<br>      chrome.driver: &quot;91.0&quot;,<br>    };</pre><p><strong>Step 6:</strong> Now, let us write our test script inside our test method using Selenium and JavaScript. I am making use of the <strong>dragAndDrop()</strong> and passing source and target web elements to achieve the drag and drop action here.</p><pre>//To wait for browser to build and launch properly<br>    var driver = await new Builder()<br>      .usingServer(gridUrl)<br>      .withCapabilities(capabilities)<br>      .build();<br> <br>    //To launch the website<br>    await driver.get(<br>      &quot;<a href="https://www.lambdatest.com/selenium-playground/drag-and-drop-demo">https://www.lambdatest.com/selenium-playground/drag-and-drop-demo</a>&quot;<br>    );<br> <br>    //To locate the source and target elements<br>    let draggable = driver.findElement(By.id(&quot;draggable&quot;));<br>    let droppable = driver.findElement(By.id(&quot;droppable&quot;));<br> <br>    //To perform drag and drop operation<br>    await driver.actions().dragAndDrop(draggable, droppable).perform();<br> <br>    //To verify drop success/fail by validating the text inside target element<br>    let targetText = await droppable.getText();<br>    if (targetText === &quot;Dropped!&quot;) {<br>      console.log(&quot;PASS: Source is dropped at location&quot;);<br>    } else {<br>      console.log(&quot;FAIL: Source is not dropped at location&quot;);<br>    }<br> <br> <br>    //It is always a safe practice to quit the browser after execution<br>    await driver.quit();</pre><p>Our final code looks like this.</p><pre>const USERNAME = &quot;YOUR_USERNAME&quot;; //replace with your username<br>const KEY = &quot;YOUR_ACCESSKEY&quot;; //replace with your access key<br> <br>const GRID_HOST = &quot;hub.lambdatest.com/wd/hub&quot;;<br>const gridUrl = &quot;https://&quot; + USERNAME + &quot;:&quot; + KEY + &quot;@&quot; + GRID_HOST;<br> <br>const { Builder, Key, By } = require(&quot;selenium-webdriver&quot;);<br> <br>async function example() {<br>  try {<br>    var capabilities = {<br>      build: &quot;Drag and Drop&quot;,<br>      name: &quot;Drag and Drop&quot;,<br>      platform: &quot;Windows 10&quot;,<br>      browserName: &quot;Chrome&quot;,<br>      version: &quot;91.0&quot;,<br>      selenium_version: &quot;4.0.0&quot;,<br>      chrome.driver: &quot;91.0&quot;,<br>    };<br> <br>    //To wait for browser to build and launch properly<br>    var driver = await new Builder()<br>      .usingServer(gridUrl)<br>      .withCapabilities(capabilities)<br>      .build();<br> <br>    //To launch the website<br>    await driver.get(<br>      &quot;<a href="https://www.lambdatest.com/selenium-playground/drag-and-drop-demo">https://www.lambdatest.com/selenium-playground/drag-and-drop-demo</a>&quot;<br>    );<br> <br>    //To locate the source and target elements<br>    let draggable = driver.findElement(By.id(&quot;draggable&quot;));<br>    let droppable = driver.findElement(By.id(&quot;droppable&quot;));<br> <br>    //To perform drag and drop operation<br>    await driver.actions().dragAndDrop(draggable, droppable).perform();<br> <br>    //To verify drop success/fail by validating the text inside target element<br>    let targetText = await droppable.getText();<br>    if (targetText === &quot;Dropped!&quot;) {<br>      console.log(&quot;PASS: Source is dropped at location&quot;);<br>    } else {<br>      console.log(&quot;FAIL: Source is not dropped at location&quot;);<br>    }<br> <br>    //It is always a safe practice to quit the browser after execution<br>    await driver.quit();<br> <br>  } catch (err) {<br>    handleFailure(err, driver);<br>  }<br>}<br> <br>example();<br> <br>function handleFailure(err, driver) {<br>  console.error(&quot;Something went wrong!\n&quot;, err.stack, &quot;\n&quot;);<br>  driver.quit();<br>}</pre><p>Additionally, I have added a try-catch block for error handling. Also have provided the function call to execute the method on run command.</p><p><strong>Step 7:</strong> Execute the test. Make sure you are in the right folder and give the following command in the terminal.</p><pre>node test.js</pre><p>The <strong>test.js</strong> file starts executing, and you can observe your live test running status on your TestMu AI Dashboard along with a detailed report containing video and logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unO9MEFsa0e1siAMOgMgVA.png" /></figure><p>TestMu AI helps you track the state of your automated tests by showing a clear view of the tests that have passed, failed, and are still in progress. You can go through TestMu AI<a href="https://analytics.lambdatest.com/test-overview?utm_source=medium&amp;utm_medium=Organic&amp;utm_campaign=mar_29&amp;utm_term=rd&amp;utm_content=webpage"> Analytics</a> to help you gain insight into your automated testing efforts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*t7710qab7t66WpBq6nHDYQ.png" /></figure><p>Similarly, you can run your test case in multiple browsers by defining the appropriate capabilities in your test file.</p><ol><li>Firefox browser</li></ol><pre>var capabilities = {<br>      build: &quot;Drag and Drop&quot;,<br>      name: &quot;Drag and Drop&quot;,<br>      platform : &quot;Windows 10&quot;,<br>      browserName : &quot;Firefox&quot;,<br>      version : &quot;86.0&quot;,<br>      selenium_version : &quot;4.1.0&quot;,<br>      driver_version : &quot;v0.36.0&quot;<br>    };</pre><p>2. Safari browser</p><pre>var capabilities = {<br>      build: &quot;Drag and Drop&quot;,<br>      name: &quot;Drag and Drop&quot;,<br>      platform: &quot;MacOS Monterey&quot;,<br>      browserName: &quot;Safari&quot;,<br>      version: &quot;15.0&quot;,<br>      selenium_version: &quot;4.0.0&quot;,<br>      driver_version: &quot;v0.36.0&quot;,<br>    };</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usrliixCb-jZq5OJNbWOXA.png" /></figure><p>2. Using dragAndDrop() by passing X and Y offsets</p><p>In the above section of this article on how to implement drag and drop in JavaScript, we passed the source and target elements to drag and drop. Now, let us see the code to automate drag and drop by passing x and y offset values.</p><p>The updated code for the test method is as below:</p><pre>var driver = await new Builder()<br>      .usingServer(gridUrl)<br>      .withCapabilities(capabilities)<br>      .build();<br> <br>    //To launch the website<br>    await driver.get(<br>      &quot;<a href="https://www.lambdatest.com/selenium-playground/drag-and-drop-demo">https://www.lambdatest.com/selenium-playground/drag-and-drop-demo</a>&quot;<br>    );<br> <br>    //To locate the source elements <br>    let draggable = driver.findElement(By.id(&quot;draggable&quot;));<br> <br>    //To perform drag and drop by offset<br>    await driver.actions().dragAndDrop(draggable, { x: 50, y: 50 }).perform();<br> <br>    await driver.quit();</pre><p>You can also go through the Selenium JavaScript Tutorial to dive deep into how Selenium WebDriver with JavaScript can be used for automated testing of web applications.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBQ-9e13kJ58%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBQ-9e13kJ58&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBQ-9e13kJ58%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe53ae2d99cc3092e39128d947cff6c7/href">https://medium.com/media/fe53ae2d99cc3092e39128d947cff6c7/href</a></iframe><p>Note: Using JSON.stringify() and JSON.parse(), you can convert JavaScript objects to JSON strings and JSON strings back to JavaScript objects.</p><h3>Conclusion</h3><p>Selenium WebDriver provides Actions class, which can be leveraged to automate complex user interactions in the browser like Drag and Drop. In this JavaScript drag and drop tutorial, we explored what is Actions class in Selenium is and how to implement drag and drop in JavaScript while performing Selenium automation testing. Hoping this blog turned out to be beneficial.</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e2b4ca5dbf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Use Deep Selectors In Selenium WebdriverIO]]></title>
            <link>https://haritaravindranath.medium.com/how-to-use-deep-selectors-in-selenium-webdriverio-7bc0f92f76a4?source=rss-334efde8368f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bc0f92f76a4</guid>
            <dc:creator><![CDATA[Harita Ravindranath]]></dc:creator>
            <pubDate>Wed, 23 Mar 2022 06:20:20 GMT</pubDate>
            <atom:updated>2026-10-21T09:28:49.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*cG7Uhy74gMxZChat080nxQ.jpeg" /></figure><p><em>LambdaTest is now TestMu AI. This article was first published on the </em><a href="https://www.testmuai.com/blog/deep-selectors-in-selenium-webdriverio/"><em>TestMu AI blog</em></a><em>.</em></p><p>WebdriverIO is one of the most <a href="https://www.testmuai.com/blog/top-javascript-testing-frameworks/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=mar23&amp;utm_term=rd&amp;utm_content=blog">popular automation testing frameworks</a> that is extensively adopted by testers at a global level. It is an open-source progressive test automation framework built to automate web, mobile, and native desktop applications by leveraging the power of the Webdriver protocol. The framework is highly extensible and feature-rich, offering a wide variety of plugins to fulfill your requirements.</p><p>One of the key features of WebdriverIO that distinguishes it from the other frameworks in the market is its advanced smart selector strategies. Identifying a UI element on the application screen is the primary activity of any test automation framework, and for this, locators (or selectors, as addressed by WebdriverIO official documentation) are used.</p><p>In this <a href="https://www.testmuai.com/learning-hub/webdriverio/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=mar23&amp;utm_term=rd&amp;utm_content=learning_hub">Selenium WebdriverIO tutorial</a>, we will focus on learning Deep Selectors or WebdriverIO selectors and how to use them when writing tests. Before beginning with WebdriverIO selectors, we will also briefly understand Selenium locators in WebdriverIO and the different types of selectors supported by the framework.</p><p>Let’s get started!</p><h3>What are Selectors in WebdriverIO</h3><p>Selectors or <a href="https://www.testmuai.com/learning-hub/selenium-locators/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=mar23&amp;utm_term=rd&amp;utm_content=learning_hub">Selenium Locators</a> are Selenium commands that enable us to find or locate any WebElement on a web page when an automation test is executed. Upon reading these selector commands from the script, the Selenium library converts it into an HTTP request and interacts with browsers leading to performing the actions based on the command.</p><p>ElementNotSelectableException raised when client script trying to select is an element which is not selectable.</p><p>WebdriverIO supports different types of selector strategies. Some of the most commonly used WebdriverIO selectors are listed below:</p><ul><li>CSS Query Selector</li><li>Link Text</li><li>Partial Link Text</li><li>Element with certain text</li><li>Tag Name</li><li>Name</li><li>Id</li><li>XPath</li><li>JS Function</li><li>Chain Selectors</li><li>React Selectors</li><li>Mobile Selectors</li><li>Custom Selectors etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*4D2UovcsEFTIk8Y_LMKpyg.jpeg" /></figure><p>Before moving on to WebdriverIO selectors, it is crucial to understand the problem it is trying to solve. In the upcoming sections of this Selenium WebdriverIO tutorial, we will be discussing Shadow DOM and how the WebdriverIO selectors come in handy in such scenarios. However, feel free to skip these sections if you are already familiar with the concepts.</p><h3>How to work with Shadow DOM?</h3><p>The concept of the Document Object Model (DOM) is familiar to all of us. But what is a Shadow DOM? In this section of the Selenium WebdriverIO tutorial, we will familiarise what is meant by Shadow DOM and the reason behind its growing importance in the field of web development &amp; testing.</p><p>The concept of shadow DOM was conceived as a result of evolution in the web development field, focusing on “code isolation” or “encapsulation.” The shadow DOM can be defined as a web standard used by developers to encapsulate their HTML code and style components for creating a sub-DOM so that no other style components can override this code.</p><p>This means that the shadow DOM allows specific sections of the HTML document to be completely isolated from the other components in the DOM. This isolated code is unaffected by any modifications made to other DOM elements. Over &amp; above, the CSS styles applied to DOM elements are not applicable to shadow DOM and vice versa. Using the concept of shadow DOM, developers can now build web components that are highly portable and reusable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*sYgDgVpnh7tzXkiDWXSBNA.jpeg" /></figure><p>Some of the key terminologies used in shadow DOM are:</p><ul><li><strong>Shadow host</strong>: The regular DOM node that is attached to the shadow DOM.</li><li><strong>Shadow tree</strong>: The DOM tree inside the shadow DOM.</li><li><strong>Shadow boundary</strong>: The place where the shadow DOM ends and the regular DOM begins.</li><li><strong>Shadow root</strong>: The root node of the shadow tree.</li></ul><p>A shadow DOM has two different modes:</p><ul><li>Open mode</li><li>Close mode</li></ul><p>The difference between these two modes lies in their public accessibility.</p><p>A shadow root can be attached to any element using the Element.attachShadow() method.</p><pre>let shadow = elementRef.attachShadow({mode: &#39;open&#39;});let shadow = elementRef.attachShadow({mode: &#39;closed&#39;});</pre><p>If the mode is set as open, you can access the shadow DOM using the Element<strong>.shadowRoot</strong> property of JavaScript, and if it is set to be close, null is returned.</p><pre>let myShadowDom = myCustomElem.shadowRoot;</pre><p>To examine a real-world application, let us inspect the DOM structure of Google Chrome downloads. First, open the Google Chrome browser and go to chrome://downloads/ and inspect the page using Developer Tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q3UUjYF-zx9IOI29KJ9-_w.png" /></figure><p>Notice the #shadow-root element as it represents a shadow root, and the mode is set as open. All elements inside this #shadow-root are shown considered separate from the current DOM document.</p><h3>What are Deep Selectors in WebdriverIO?</h3><p>The Shadow DOM is one among the four specifications created for web components. Although it is a useful and powerful solution for developers, they often pose a challenge for testers. This is because the DOM query functions used by automation testing frameworks would not work properly on shadow DOM elements. This is because they technically do not exist in the main DOM. In this section of the Selenium WebdriverIO tutorial, we will explore how WebdriverIO can help automation testers by tackling this problem.</p><p>By now, we have understood we need special workarounds for handling shadow DOM elements. Initially, WebdriverIO selectors offered two flavors: shadow$ and shadow$$ to access an element inside a given element’s shadowRoot. But they had their limitations especially when it comes to working with lots of nested shadow roots. Hence, Deep selectors were introduced as an alternative approach. Using Deep selectors, you can now query all elements within any shadow DOM using the common query command.</p><p>Let us check out a sample code from the official documentation. Given below is the structure of an application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svRD8VQrx8V3GUxgw6kWzA.png" /></figure><p>In order to query the &lt;button /&gt; element which is nested within another shadow DOM, you can use the following selector:</p><pre>const button = $(&#39;&gt;&gt;&gt;.dropdown-item:not([hidden])&#39;)<br>console.log(button.getText()) // outputs: &quot;Open downloads folder&quot;</pre><h3>Writing a test using Deep Selectors in WebdriverIO</h3><p>Through the previous sections, we received a basic understanding of the Deep Selectors strategy provided by WebdriverIO. Now it is time to get our hands dirty. In this section of the Selenium WebdriverIO tutorial, we will see how to write an automation test case by accessing shadow DOM using WebdriverIo selectors.</p><p>First of all, let us quickly set up and install the WebdriverIO framework. Make sure that the following prerequisites are installed in your machine before getting started.</p><ul><li>NodeJS and NPM</li><li>Visual Studio Code as IDE (or any other IDE of choice)</li></ul><p>Also, please note that we will be using JavaScript with Mocha for this demonstration purpose. If you are new to Mocha, please refer to our blog on Mocha JavaScript Tutorial With Examples For Selenium Testing. With that said, let us proceed with the installation.</p><p>If you’re curious about the world of Mocha, this video will teach you to write and run your first test case in Mocha. You’ll learn about using the command-line interface, configuration files, and more.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhUDQOcabs0Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhUDQOcabs0Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhUDQOcabs0Y%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c9511d1154c2576180713dc3f37acac/href">https://medium.com/media/8c9511d1154c2576180713dc3f37acac/href</a></iframe><p><strong>Step 1:</strong> Create a project folder in the desired location in your system. Open the folder in the preferred IDE.</p><p><strong>Step 2:</strong> Initialize the project with the package.json file.</p><ol><li>Open the terminal in VS Code.</li><li>Verify whether it is pointing to the project folder.</li><li>Trigger the following command on the terminal to initialize the project:<br>npm init -y</li><li>With this, we have successfully created the package.json file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*Euxg5nRhV4Q2npLaRJPlpA.png" /></figure><p><strong>Step 3:</strong> Install dependencies. Install the CLI tool for WebdriverIO.</p><pre>npm install --save-dev <a href="http://twitter.com/wdio/cli">@wdio/cli</a></pre><p><strong>Step 4:</strong> Set up the configuration file.</p><pre>npx wdio config</pre><p>You will be prompted to choose the configurations for getting started. Select the options accordingly, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*OhsmNSUzh_8Xq7aiH4gfCg.png" /></figure><p>And that’s pretty much with the setting up and configuration of the WebdriverIO framework. Notice that our project folder structure will now look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*BZSmXuc95FecJVVZWzR9JQ.png" /></figure><p>Now let’s move on to writing tests. Note that we are not implementing any advanced features like the Page Object Model as this is a simple demo.</p><p>We will be implementing the following scenario through this test.</p><ol><li>Open Google chrome downloads page.</li><li>Verify the page header is visible (which is located inside shadow DOM).</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyJ8uO06hp_23YTURLEtRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*WjGt_wfnUXzlGAJPeUi2gQ.png" /></figure><p>Let us script our first test case through the following steps.</p><p><strong>Step 1:</strong> We will be creating our test script inside the <strong>tests/specs</strong> folder. Create a test file with a meaningful name ending with the .js extension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*kUS2ILLPsdKm0EMJI33TSQ.png" /></figure><p><strong>Step 2</strong>: Write the following code structure inside your test file.</p><pre>describe(&#39;Verify Downloads&#39;, () =&gt; {<br>    it(&#39;Validate downloads page header text&#39;, async () =&gt; {<br>     <br>    });<br>});</pre><p><strong>Step 3</strong>: Write the test steps inside the snippet and complete the code.</p><pre>//to navigate to downloads page<br>        await browser.url(https://medium.com/%60chrome://downloads/%60);<br>        //to verify the container downloads-manager is existing<br>        await expect($(&#39;body &gt; downloads-manager&#39;)).toBeExisting();<br>        //to verify the page header located inside shadow DOM using deep selector &gt;&gt;&gt;<br>        await expect($(&#39;&gt;&gt;&gt;#leftSpacer h1&#39;)).toHaveTextContaining(&#39;Downloads&#39;);</pre><p>Overall code structure will look like this:</p><pre>describe(&#39;Verify Downloads&#39;, () =&gt; {<br>    it(&#39;Validate downloads page header text&#39;, async () =&gt; {<br>        await browser.url(https://medium.com/%60chrome://downloads/%60);<br>        await expect($(&#39;body &gt; downloads-manager&#39;)).toBeExisting();<br>        await expect($(&#39;&gt;&gt;&gt;#leftSpacer h1&#39;)).toHaveTextContaining(&#39;Downloads&#39;);<br>    });<br>});</pre><p><strong>Step 4</strong>: Run the test using the following command:</p><pre>npx wdio wdio.conf.js</pre><p>The test starts running. The <a href="https://www.testmuai.com/virtual-browsers/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=mar23&amp;utm_term=rd&amp;utm_content=webpage">virtual browser</a> gets launched, and the code is executed successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*M759cOQ2iB33pDMajRsDkQ.png" /></figure><p>IME (Input Method Engine), Selenium needs it to support Japanese/Chinese or multi-byte characters that needs to write by selenium in a web form. when selenium is not able to find the desired IME engine on the machine then it throws ImeNotAvailableException</p><h3>Executing the test case on a cloud Selenium Grid</h3><p>In the last section, we ran our test script in the local machine. In this section of the Selenium WebdriverIO tutorial, we will additionally explore how we can perform cross browser testing using <a href="https://www.testmuai.com/webdriverio-testing/?utm_source=medium&amp;utm_medium=organic&amp;utm_campaign=mar23&amp;utm_term=rd&amp;utm_content=webpage">WebdriverIO</a> on a cloud-based Selenium Grid.</p><p>Adopting a cloud-based grid as an automation backend is a popular strategy adopted by companies worldwide to stay ahead in the market competition. In addition, cross browser testing and test coverage need no introduction in the testing domain. Both of the strategies combined help us deliver a quality product at a faster pace by testing that the app works as expected in all possible OS, device, and browser versions. The even better news is that the WebdriverIO framework natively supports cloud-based testing platforms like TestMu AI.</p><p>TestMu AI (formerly LambdaTest) is an AI-native software testing cloud that helps developers and QA teams automate end-to-end testing across web, mobile, and AI applications.</p><p>With few minor configuration changes, we can run our test cases in the online Selenium Grid provided by the TestMu AI platform. Let us see how.</p><p><strong>Step 1</strong>: In your project terminal, give the following command to save the TestMu AI service as a devDependency.</p><pre>npm i --save-dev wdio-lambdatest-service</pre><p><strong>Step 2</strong>: Create a free account or log in to your TestMu AI Account. Fetch your unique username and access key. You can find the details in the <a href="https://accounts.lambdatest.com/detail/profile">TestMu AI Profile section</a>.</p><p><strong>Step 3</strong>: Now, we need to edit the wdio.conf.js configuration file as shown below.</p><pre>user= process.env.LT_USERNAME || &quot;your_username&quot;,<br>key= process.env.LT_ACCESS_KEY || &quot;your_accesskey&quot;,<br> <br>exports.config = {<br>    user,<br>    key,<br>    specs: [<br>        &#39;./test/specs/**/*.js&#39;<br>    ],<br>    exclude: [],<br> <br>    capabilities: [{   <br> <br>        name: &quot;DeepSelectors Testing&quot;,<br>        build: &quot;DeepSelectors&quot;,<br>        maxInstances: 5,<br>        browserName: &#39;chrome&#39;,<br>        version:&quot;64.0&quot;,<br>        acceptInsecureCerts: true,<br>        network: true,<br>        video: true,<br>        visual: true,<br>        console: true,<br> <br>    }],<br> <br>    logFile : &#39;./logDir/api.log&#39;,<br>    services: [<br>        [&#39;lambdatest&#39;, {<br>            tunnel: true<br>        }]<br>    ],<br>    hostname: &#39;hub.lambdatest.com&#39;,<br>    path: &#39;/wd/hub&#39;,<br>    port: 80,<br> <br>    baseUrl: &#39;&#39;,<br>    maxInstances: 10,<br>    logLevel: &#39;info&#39;,<br>    bail: 0,<br> <br>    waitforTimeout: 10000,<br>    connectionRetryTimeout: 120000,<br>    connectionRetryCount: 3,<br>    <br>    framework: &#39;mocha&#39;,<br>    reporters: [&#39;spec&#39;],<br>    mochaOpts: {<br>        ui: &#39;bdd&#39;,<br>        timeout: 60000<br>    } <br>}</pre><p>Following are the changes to be made:</p><ul><li>Pass your access token and user details by creating two variables, user and key.</li><li>Set the tunnel as true to enable routing connections from TestMu AI cloud through your computer.</li><li>Set the hostname corresponding to TestMu AI.</li><li>You can also enable report formats like video recording, console, network logs, etc., to be true.</li></ul><p><strong>Step 4</strong>: Run the test.</p><pre>npx wdio wdio.conf.js</pre><p>You can observe the live test running status in your <a href="https://automation.lambdatest.com/timeline">TestMu AI Automation Dashboard</a> of the TestMu AI account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-n8Ecxy3DTdhqdSbVNfCA.png" /></figure><p>The test has been executed successfully. To analyze the detailed report, visit the Automation Logs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0lZ77DI9YjBNOCnFShPWw.png" /></figure><p>IME (Input Method Engine), Selenium needs it to support Japanese/Chinese or multi-byte characters that needs to write by selenium in a web form. when selenium is failed to activate the desired input method engine then it throws ImeActivationFailedException</p><h3>Conclusion</h3><p>The shadow DOM is a powerful concept heavily relied upon during frontend development, which is designed to create an isolated DOM with scoped CSS. However, for the testers, they often pose a challenge as additional workarounds are required to access the elements located inside shadow DOM to write the test script. Deep Selectors is a selector strategy implemented by the popular Selenium framework, WebdriverIO, to tackle this problem of accessing shadow DOM elements.</p><p>In this Selenium WebdriverIO tutorial, we discussed WebdriverIO selectors and how to utilize them while writing a test case in the WebdriverIO framework. Additionally, we also checked out how to run our test cases on the cloud-based Selenium Grid platform provided by TestMu AI to achieve cross browser testing and test coverage. I hope that this tutorial enables you to adopt Deep Selectors into your project.</p><p>Happy Testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bc0f92f76a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>