Select Page

Category Selected: Automation Testing

152 results Found


People also read

OTT Testing

Hidden Hurdles: Challenges in OTT Platform Testing

Automation Testing

Playwright Cheatsheet: Quick Tips for Testers

Automation Testing

A Quick Playwright Overview for QA Managers

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility
An Introductory Action Class Guide for Beginners

An Introductory Action Class Guide for Beginners

If you are going to test an application using Selenium WebDriver, you most definitely will face scenarios where you will be needed to trigger keyboard and mouse interactions. This is where our Action Class Guide comes into the picture. Basically, Action Class is a built-in feature provided by Selenium for simulating various events and acts of a keyboard and mouse. With the help of Action classes, you will be able to trigger mouse events like Double Click, Right Click, and many more events. The same goes for keyboards as well, you can trigger the functions of CTRL key, CTRL + different keys, and other such combinations. As one of the best QA companies, we have been able to use Action Class to its zenith by using it in various combinations as per the project needs. But before exploring such Action class implementations, let’s take a look at some basics.

Action Class Guide for MouseActions

So we wanted to start our Action Class Guide by listing some of the most frequently used mouse events available in the Action class.

click() – Clicks on the particular WebElement (Normal Left Click)

contextClick() – Right clicks on the particular WebElement

doubleClick() – Performs a double click on the WebElement

dragAndDrop (WebElement source, WebElement target) – Clicks and holds the web element to drag it to the targeted web element where it is released.

dragAndDropBy(WebElement source, int xOffset, int yOffset) – Clicks and Drag the element to the given location using offset values

moveToElement(WebElement) – Moves the mouse to the web element and holds it on the location (In simple words, the mouse hovers over an element)

moveByOffset(int xOffSet, int yOffSet) – Moves the mouse from the current position to the given left (xOffset value) and down (yOffset Value).

clickAndHold(WebElement element) – Clicks and holds an element without release.

release() – Releases a held mouse click.

Action Class Guide Keyboard Actions

Same as above, we have listed some frequently used keyboard events available in the Action class,

keyDown(WebElement, java.lang.CharSequence key) – To press the key without releasing it on the WebElement

keyUp(WebElement, java.lang.CharSequence key) – To release the key stroke on the webElement

sendkeys(value) – To enter values on WebElements like textboxes

So by including these methods, you can smoothly run your script and execute the code without any issues….

Absolutely not, we’re just kidding. We still have to gather all the action methods and execute them under the Action class.

build() – It is a method where all the actions are chained together for the action which is going to be performed.

So the above method can be used to make the actions that are to be executed ready.

perform() – It is a method used to compile and also execute the action class.
A perform method can be called alone without a build method to execute the action class methods if only one action is performed.

Action Class Guide for Performing actions

Now that we have gone through the basics, let’s find out how to implement the Action Classes in Code.

Step1:

Import the Interaction package that contains the Action Class. You can use the below line for importing,

“importorg.openqa.selenium.interactions.Actions; ”

Step2:

Create the object of the Action Class and use the Web Driver reference as the argument
Actions action = new Actions (driver)

Step3:

Once the above two steps have been completed, you can start writing your script using the Action classes and the different methods available.

Let’s proceed further and take a look at the implementation and uses of the actions available for both the mouse & keyboard.

1. SendKeys(WebElement element, value)

As stated above, this action class is mainly used to send a char sequence into the textbox. But it is also worth noting that we can use it to send the keystrokes of different key combinations likeCTRL+T, Enter, and so on.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class SendKeys {
    public static void main(String[] args) {
        WebDriver driver;        System.setProperty("webdriver.chrome.driver","D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.flipkart.com/");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        WebElement eleSearchBox = driver.findElement(By.cssSelector("input[placeholder='Search for products, brands and more']"));
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        action.sendKeys(eleSearchBox, "Iphone").build().perform();
        action.sendKeys(Keys.ENTER).build().perform();
        driver.close();
    }
}

By using the SendKeys method, an element is searched by the keystroke instead of clicking on the Search Button. (i.e.) We can clearly see in the code that the “Keys.Enter” is inside the Keys class that has various keystrokes available for the keys.

2. MoveToElement(WebElement element)

You might be in a position to test if an element changes color, shows some additional information, or performs the intended action when the mouse hovers over it. So let’s take a look at the code and find out how you can make it happen.

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.concurrent.TimeUnit;
public class MouseHover {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://www.leafground.com/");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.scrollBy(0,170)", "");
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//img[@alt='mouseover']"))).click();
        WebElement eleTabCourses = driver.findElement(By.xpath("//a[normalize-space()='TestLeaf Courses']"));
        action.moveToElement(eleTabCourses).build().perform();
        driver.close();
    }
}

We have written the above code in a way that the code first waits for the image to become clickable. Once it loads, the image gets clicked, and the mouse hovers over the element for a second.

3. DragAndDrop(source, target)

So there are basically two types of drag and drop that we will be seeing in this Action Class Guide. This is the type of action class using which we can assign a target area where the element can be dragged and dropped. Now let’s see the code to execute the DragAndDrop action,

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DragAndDrop {
        public static void main(String[] args) {
            WebDriver driver;
            System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
            driver = new ChromeDriver();
            driver.get("http://www.leafground.com/");
            driver.manage().window().maximize();
            Actions action = new Actions(driver);
            driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
            driver.findElement(By.xpath("//h5[normalize-space()='Droppable']")).click();
            WebElement eleSource = driver.findElement(By.xpath("//div[@id='draggable']"));
            WebElement eleTarget = driver.findElement(By.xpath("//div[@id='droppable']"));
            action.dragAndDrop(eleSource,eleTarget).build().perform(););
            driver.close();
        }
}

For dragging an element to the dropped place, first, the locators are captured for the source and target. Following this, they are passed inside the action method using dragAndDrop.

4. DragAndDropBy(WebElement source,int xOffset, int yOffSet )

So we have already seen how to drag a drop an element within a targeted area, but what if we would like to drag and drop an element by a defined value? Let’s take a look at the code and find out how.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DragAndDropOffset {
        public static void main(String[] args) throws InterruptedException {
            WebDriver driver;
            System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
            driver = new ChromeDriver();
            driver.get("http://www.leafground.com/");
            driver.manage().window().maximize();
            Actions action = new Actions(driver);
            driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
            driver.findElement(By.xpath("//img[@alt='Draggable']")).click();
            WebElement eleDrag= driver.findElement(By.xpath("//div[@id='draggable']"));
            action.dragAndDropBy(eleDrag,200,130).build().perform();
            Thread.sleep(2000);
            driver.close();
        }
    }

In the above code, we have used the DragAndDropBy method in a way that it clicks and moves the element to the offset position as specified and releases it once the target location is reached.

5. Click(WebElement element)

There is no way to test anything without being able to use the left click button. So let’s find out the code to execute this very basic and necessary functionality.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class LeftClick {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        driver.manage().window().maximize();
        Actions actions = new Actions(driver);
        WebElement eleInput = driver.findElement(By.name("q"));
        actions.sendKeys(eleInput, "www.codoid.com").build().perform();
        WebElement BtnSearch = driver.findElement(By.xpath("//div[@class='FPdoLc lJ9FBc']//input[@name='btnK']"));
        actions.click(BtnSearch).build().perform();
        driver.close();
    }
}

6. ContextClick(WebElement element)

Though the right-click is not used as commonly as the left click, it is still a very basic functionality every tester must know. So let’s take a look at the code to find out how to implement it.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class RightClick {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://demo.guru99.com/test/simple_context_menu.html");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        WebElement eleRightClick = driver.findElement(By.xpath("//span[@class='context-menu-one btn btn-neutral']"));
        action.contextClick(eleRightClick).perform();
        driver.close();
    }
}

It is worth mentioning here that we have not used ‘build’ anywhere in the above code. Instead, we have used ‘perform’ to execute the functionality.

7. DoubleClick(WebElement element)

Just like the previous functionalities we have seen in the Action Class Guide, double-click is another basic functionality that is vital to any form of testing. So let’s jump straight to the code.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class DoubleClick {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://demo.guru99.com/test/simple_context_menu.html");
        driver.manage().window().maximize();
        Actions action = new Actions(driver);
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        WebElement eleDoubleClick = driver.findElement(By.xpath("//button[normalize-space()='Double-Click Me To See Alert']"));
        action.doubleClick(eleDoubleClick).perform();
        driver.quit();
    }

8. KeyDown(WebElement element, Modifier Key) & KeyUp (WebElement element, Modifier Key)

CTRL, SHIFT, and ALT are few examples of modifier keys that we all use on a day-to-day basis. For example, we hold down Shift if we want to type something in caps. So when we use the KeyDown action class, it holds a particular key down until we release it using the KeyUp action class. With that said, let’s see an example code in which we have used these functionalities,

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class KeyDownAndKeyUp {
    public static void main(String[] args) {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        driver.manage().window().maximize();
        Actions actions = new Actions(driver);
        WebElement eleInput = driver.findElement(By.name("q"));
        actions.click(eleInput).build().perform();
        actions.keyDown(eleInput, Keys.SHIFT);
        actions.sendKeys("eiffel tower");
        actions.keyUp(eleInput,Keys.SHIFT);
        actions.sendKeys(Keys.ENTER);
        actions.build().perform();
        driver.close();
    }
}

So if you have taken a look at the code, it is evident that once we have used the KeyDown method, the Shift key was pressed down. So the text ‘eiffel tower’ that was fed in the next line would have gotten capitalized. Now that the KeyDown has solved its purpose in this scenario, we have used to KeyUp method to release it.

9. MoveByOffset(int xOffSet, int yOffSet)

As seen above, ByOffset(int x, int y) is used when we need to click on any particular location. We can do this by assigning locations for the x and y axes. Now let’s explore the code that we have used for execution.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class MoveByOffSet {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        driver.manage().window().maximize();
        Actions actions = new Actions(driver);
        WebElement eleInput = driver.findElement(By.name("q"));
        actions.sendKeys(eleInput, "Eiffel").build().perform();
        actions.sendKeys(Keys.ENTER).build().perform();
        Thread.sleep(2000);
        actions.moveByOffset(650, 300).contextClick().build().perform();
        driver.close();
    }
}

10. ClickAndHold(WebElement element)

The action method that we will be seeing now in our Action Class Guide can be used when an element has to be clicked and held for a certain period of time.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class ClickAndHold {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.google.com/");
        driver.manage().window().maximize();
        Actions actions = new Actions(driver);
        WebElement eleInput = driver.findElement(By.name("q"));
        actions.sendKeys(eleInput, "Flower").build().perform();
        actions.moveByOffset(500,300).click().build().perform();
        Thread.sleep(2000);
        WebElement BtnSearch = driver.findElement(By.xpath("//div[@class='FPdoLc lJ9FBc']//input[@name='btnK']"));
        actions.clickAndHold(BtnSearch).build().perform();
        driver.close();
    }
}

In the above code, we have first opened Google and then searched using ‘Flower’ as the input and then performed a left-click action at the defined location. After which, we have performed a click and hold action on the search button.

Note:

In addition to that, if we need the click to be released, we can use the release method to release the clicked element before using ‘build’.

actions.clickAndHold(BtnSearch).release().build().perform();

Uploading a File Using SendKeys Method:

We know that the SendKeys action method can be used to send a character sequence. But one interesting way to use it would be to upload a normal document. If you’re wondering how that is possible, let’s take a look at the code,

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class FileUpload {
    public static void main(String[] args) throws InterruptedException {
        WebDriver driver;
        System.setProperty("webdriver.chrome.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("http://www.leafground.com/");
        driver.manage().window().maximize();
        driver.findElement(By.xpath(" //img[@alt='contextClick']")).click();
        WebElement eleSendFile = driver.findElement(By.cssSelector("input[name='filename']"));
        eleSendFile.sendKeys("C:\\Users\\OneDrive\\Desktop\\Sample.txt");
        Thread.sleep(2000);
        driver.close();
    }
}

In the above code, we have used the SendKeys action method to enter the file’s address path to locate the object that has to be uploaded. The document which we have used here is an input type document as this type of document is only ideal for sending the document using SendKeys.

Note:

Just in case you are not using Google Chrome and would like to execute these action class methods in Mozilla Firefox, all you have to do is just add the driver and set the system property for the gecko driver and initialize the driver object for it using the below line.

System.setProperty("webdriver.gecko.driver", "D:\\ActionClass\\src\\test\\java\\Drivers\\geckodriver.exe");
driver = new FirefoxDriver();

Conclusion:

We hope you have enjoyed reading our introductory action class guide that has covered the basic action class methods starting from a basic ‘Click’ to uploading a file using ‘SendKeys’. Action class helps one to perform all the basic actions on a webapp.Release() method, which can be used to release any element that was clicked or held. ‘Perform’ can be used alone, but if there are more composite actions, build and perform should be used together. As a leading test automation company, we are well aware of how resourceful action classes can be when used effectively. Once you have understood the basics, you would be able to perform so many more actions by using combinations of the action methods established in this blog.

Most Common Automation Problems QA Teams Still Face

Most Common Automation Problems QA Teams Still Face

One of the big trends that rose in popularity in 2020 is test automation and it’s still one of the hottest trends today. This has been the answer that made many believe in the potential of CI/CD and quick QA processes. But even with its perks, many teams are still struggling to achieve its benefits because of the issues they encounter when implementing and working with test automation. 

The biggest misconception of test automation is that you’re pretty much set once you have onboard this process. Truthfully, the reality is far from that. Thorough and careful planning is needed, that’s why partnering up with a reliable automation testing company can do loads to help you reach your ideal business workflow. 

With that being said, it’s best to solve these problems while the iron is still hot. In this article, we’ll give you a rundown of the most common automation problems even the most seasoned QA teams still experience, so you won’t have to go through it yourself. Let’s take a look!

Problem #1: Having Unrealistic Expectations for Automated Testing

Test automation really transforms how a business operates — it saves so much time, effort, resources, and money. But with that being said, many QA teams think that once test automation is integrated into the system, things will improve rather quickly and efficiently. The truth is — not quite. 

QA teams have unrealistic expectations about automation testing, making them mess up the whole testing process. The truth is, manual testing still matters in some areas for research, and having a clear testing strategy is still vital. 

Problem #2: Introducing the Wrong Tools

QA teams’ mistake that causes problems in their automation processes is that they aren’t using the right tools. Without the right tools, test automation won’t work effectively, and with the plethora of software and tools in the market, it’s quite easy to feel overwhelmed. 

The best way to deal with this is by working with an automation testing company that could help you choose the best tools that would help you reach your goals. Together, you can set requirements, such as your budget and what kind of support your team needs, then look for a tool that fits just that. 

Problem #3: Choosing Wrong Tests to Automate

When you integrate test automation in your business operations, it could be the shiny new toy your QA team may have, preventing you from choosing the right tests to focus on. With that, you risk missing out on important scenarios and gaps in software quality.

With that being said, choose tests that are worth automating. As you integrate test automation in your workflow, assess which cases need this type of approach and be more beneficial for the team. Besides that, it helps look for potential weak spots in your system to avoid any mishaps during the testing. 

Problem #4: Lack of Training for Testing

Among all the QA team problems, this is by far the trickiest. Without proper training, all your strategies and automation testing efforts may go to waste. With poor training, your team won’t develop an effective and consistent system that could help create a powerful testing approach. 

So before implementing automation, it’s best to train your team correctly and work with an automation testing provider, like Codoid, who could help your team throughout this significant change. With clarity, your team will develop enough technical skills to support your automated tests.

The Bottom Line: You Need to Do the Work to Make Test Automation Do Its Job

Many business leaders reap the benefits of test automation, but we can all agree that reaching this isn’t a walk in the park. The unrealistic expectations that people have over the whole process cause teams to underestimate the importance of a solid strategy, creating gaps in product quality.

With that being said, it’s best to work with automation testing companies, so you know exactly what you’re dealing with and how to maximize the potential of this incredible tool.

Work With Codoid

Seeing as test automation can be quite challenging to deal with, it’s best to work with industry leaders in QA, such as Codoid.

Here at Codoid, we are passionate about guiding and leading the Quality Assurance community in creating better strategies that would help develop and expand their companies. We offer various testing services, such as automation, mobile, performance, gaming, analytics testing, and more. 

We also speak at software testing groups, software quality assurance events, and automation testing conferences. If you’re looking for automation testing companies that would help develop your QA team, speak to us today — we’re happy to help!

TestNG Tutorial : An Introduction to its Attributes and Features

TestNG Tutorial : An Introduction to its Attributes and Features

TestNG is not the only option available in the market. But most of the automation testers prefer TestNG over other options like JUnit because TestNG allows parallel execution of test cases that saves loads of time possible with the help of the ‘parallel’ keyword in the XML file, TestNG’s seamless integration with tools like Jenkins, Maven, etc., and grouping of test cases also becomes easy with the use TestNG. These features have been instrumental in us providing the best software testing services to our clients. So in this TestNG tutorial, we will be focusing on how to make use of all these advantages and also explore all the advantages that TestNG brings to the table.

TestNG is an open-source testing framework where NG stands for Next Generation. It provides many features to execute the test methods by using various annotations like @Test @BeforeTest, @BeforeClass, etc. TestNG allows its users to generate robust test results that include the number of test cases that have Run, Passed, Failed, and Skipped. It can also be used to implement the logging feature using TestNG Listeners. On the whole, TestNG can also be used across various testing types like Unit, Regression, Functional, and API Testing. But before we get started with the TestNG Tutorial, let’s see how to set it up.

Installation and Setup of TestNG in IntelliJ:

IntelliJ requires a JAR file to add dependencies for TestNG script development and for running the test suites. So if it is a Maven Project, we would have to download the TestNG Jar File. Since we will be running tests on Java, we need to download an external TestNG Jar File onto our system by using the provided link.

Direct download link: TestNG/7.4.0/testng-7.4.0.jar

Reference: org.testng/TestNG

Please refer to the below image and instructions for a step-by-step guide,

Step by Step Guide

i. Open IntelliJ,

ii. Create a new JAVA Project,

iii. Navigate to ‘File’ >> ‘Project Structure’ in IntelliJ,

iv. Click on ‘Libraries’ from Project Setting,

v. Add it to your ‘TestNG’ jar file, and then click on the ‘Apply and OK’ button.

Selecting Library Files

If we want to work on a maven project, we have to mention the dependency in the POM.xml file

Maven Repository

<dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>7.4.0</version>
    <scope>test</scope>
</dependency>

TestNG Annotations:

TestNG annotations that are used to execute the test scripts can be defined by ‘@Test’ annotations. Before we head over to other aspects of the TestNG Tutorial, let’s take a look at the various annotations that are available in TestNG along with a short description of them.

Types of TestNG Annotations:

TestNG Annotation Order

@Test Annotations:

We use this annotation to mark a method as a test method. The methods marked with @Test annotation are automatically invoked by the TestNG engine in default order (i.e.) alphabetically.

Syntax:

@Test
public void TestMethod1() {
System.out.println("\n Test-Method-001");
}

So in this part of the TestNG Tutorial, we will be focusing on the most important attributes of @Test annotations, starting with the description

1. ‘Description’ attribute of @Test Annotation:

The ‘Description’ keyword is used to provide a description of the test case. It can also be termed as a one-line summary, and it has been illustrated in the below example that describes the action of the user in a single line.

@Test(description = "User visits Codoid Home page")
public void launchCodoidURL(){
System.out.println("\n >>> User visits Codoid Home page...");
}
2. Test Methods with Priority:

As mentioned earlier, we are aware that the methods will execute multiple test annotations alphabetically by default. But what if there is a need to run the methods or the test annotations based on defined priorities? Here is where the ‘Priority’ attribute comes into play, as it can be used to assign priorities to each test method. The highest priority would be given when a test method is marked with 1 and the priority decreases inversely as the number increases.

We have mentioned syntax below to denote how the priority attribute would function.

Syntax:

@Test(priority = 1)
public void Test1() {
System.out.println("\n Test-1");
}

@Test(priority = 2)
public void Test2() {
System.out.println("\n Test-2");
}
3. Test Methods with Priority & without priority:

So in the above-mentioned syntax code, we saw 2 sets of programs that had defined priorities. But what if there is a need to define priorities only for a certain number of methods? It is very easy to accomplish as you can simply leave the methods that don’t need defined priorities and mark the other methods alone in the order that you wish. It is worth noting that the methods that had no defined priority will be run first on an alphabetical basis and then followed by the defined order.

Syntax:

@Test(priority = 1)		//with Priority
public void Test1() {
System.out.println("\n Test-1");
}

@Test		//without priority
public void TestMethod1() {
System.out.println("\n Test-Method-001");
}

@Test		//without priority
public void TestMethod2() {
System.out.println("\n Test-Method-001");
}

@Test(priority = 2)		//with Priority
public void Test2() {
System.out.println("\n Test-2");
}

Code Explanation:

– Non-Prioritized methods ‘TestMethod1() and TestMethod2()’ have been executed in alphabetical order. (Line No: 60 and 65)

– Prioritized methods ‘Test1() and Test2()’ have been executed based on the priority level. (Line No: 55 and 69)

4. Depends On Methods in TestNG:

In our test scripts, we might have some methods that depend on the execution of another method before it is executed. For example, if a user wishes to send an email using the email application, then the user has to be logged in to the application first. So there will be no point in trying to send the mail if the sign-in is incomplete. So we can make use of this attribute that will help methods from getting executed if their dependent method doesn’t get a ‘Pass’. The same scenario is shown below as an example.

Syntax:

@Test
public void UserLoginIntoEmailApplication(){
    System.out.println("\n >> User Login :: ");
}
@Test(dependsOnMethods = "UserLoginIntoEmailApplication")
public void UserSendAnNewEmail(){
    System.out.println(">> User send an eMail");
}

Depends on Methods

Sometimes, there might be scenarios where a test case depends on more than one test method. So we can pass the parameters in annotations as shown below.

Syntax for dependsOnMethods: (Multiple Dependent Test methods)

@Test(dependsOnMethods = { "UserLoginIntoEmailApplication", "UserSendAnNewEmail" })
public void SignOut() {
System.out.println(">>> Sign Out");
}

Syntax for depends on Methods in TestNG

5. TestNG Groups:

The grouping concept is one of the best features of TestNG and one of the important parts of this TestNG Tutorial. So using this concept we can create a group of test methods based on modules/test cases. For example, the client requirement might demand you to execute a large number of smoke or regression tests. So you can simply pass the parameter in group attributes as shown below.

Syntax:

@Test(groups = { "Regression" })
public void userLogin() {
....
}
@Test(groups = { "Regression" })
public void userSendEmail() {
....
}

So the groups are specified in the ‘.xml’ file and can either be used with the “groups” tag name or under the ‘test’ tag.

Syntax:

<groups>
<run>
<include name = "Regression"></include>
</run>
</groups>

TestNG Groups

DataProvider in TestNG:

In this method, a user will be able to pass the test data in test methods and also iterate the test methods using different data from the @DataProvider annotation, and it will return the 2D array objects.
Let’s see a simple example for this annotation,

Code:

@DataProvider(name = "data-provider")
public Object[][] dataProviderMethod() {
return new Object[][]{{"Codoid-001"}, {"Codoid-002"}};
}
@Test(dataProvider = "data-provider")
public void testDataProviderConcept(String strData) {
System.out.println("\n >> Data: " + strData);
}

Code Explanation:

We have maintained the array object and Test methods in the same class. In this method, the “testDataProviderConcept(String strData)” will iterate based on the array size. It will also retrieve the values “Codoid-001 and Codoid-002” from the ‘dataProviderMethod()’ with the help of the @DataProvider annotation.

Data Provider in TestNG

Multiple Parameters in TestNG DataProvider:

It is even possible to pass multiple data through a single parameter. In this test method, we will be able to retrieve the data using multiple arguments as shown in the example,

For example,

@DataProvider(name = "data-provider")
public Object[][] dataProviderMethod(){
return new Object[][] {{123,456 ,789}, {001, 002, 003}};
}
@Test(dataProvider = "data-provider")
public void testMethod(int value1, int value2, int value3) {
System.out.println("\n >> value1: "+value1+"; Value2: "+value2+"; Value3: "+value3);
} 

Multiple Parameters in TestNG provider

DataProvider In TestNG Using Inheritance concept:

If you are looking for a way to maintain the code based on the project structure, then the DataProvider methods can maintain one class and the test methods can maintain another class. Let’s take a look at the example to find out how.

For example, we can access the dataprovider class using another attribute like “dataProviderClass”

Syntax :

@Test(dataProvider = “data-provider”, dataProviderClass = DP.class)

Note:

i. dataProviderClass // attribute Name

ii. DP.class // class Name; To inherit the other class.

Code:

//Class-1
@Test(dataProvider = "data-provider", dataProviderClass = DataProviderUtil.class)
public void testDataProviderConcept(String strData) {
System.out.println("\n >> Data: " + strData);
}
//Class-2  "Class Name: DataProviderUtil"
@DataProvider(name = "data-provider")
public Object[][] dataProviderMethod() {
return new Object[][]{{"Codoid-001"}, {"Codoid-002"}};

TestNG Tutorial for using Excel Workbook as a Data Provider:

Now that we have seen how to pass the parameter with single or multiple data through an array object, but what if there is a need that demands a large number of data be used? Adding everything to the code will not be an optimal choice at all. We have a solution to overcome this in our TestNG Tutorial and so let’s focus on how we can retrieve data from an Excel workbook. Knowing this will come in very handy while executing Functional tests, and when there is a need to create a large amount of test data for performing Load tests.

We are going to implement the Excel workbook in the TestNG-DataProvider annotation to fetch the data from the excel sheet and search the products in Amazon. In the example, we have listed a few mobile phones like iPhone 12, Pixel 4a, and so on in the excel sheet.

The below-mentioned Excel util class is used to retrieve the data from the Excel sheet.

ExcelUtil.JAVA

Code:


/*Description: We can retrieve the data from the Excel workbook
    * parameter-1: Excel workbook directory path,
    * parameter-2: Sheet name*/
    public static Iterator<Object[]> getTestData(String strWorkbookPath, String strWorksheetName) {
        List<Object[]> data = new ArrayList<Object[]>();
        int inRowCounter = 0;
        try {
            FileInputStream file = new FileInputStream(new File(strWorkbookPath));
            //Get the workbook instance for the xlsx file.
            HSSFWorkbook workbook = new HSSFWorkbook(file);
            //Get the first sheet from the workbook
            HSSFSheet sheet = workbook.getSheet(strWorksheetName);
            //Get an iterator to all the rows in the current sheet
            Iterator<Row> rowIterator = sheet.rowIterator();
            Row firstRow = rowIterator.next();
            Map<String, String> columnNamesMap = getColumnNames(firstRow);
            while (rowIterator.hasNext()) {
                Iterator<Cell> cellIterator = rowIterator.next().cellIterator();
                Map<String, String> rowMap = new LinkedHashMap();
                for (Entry entry : columnNamesMap.entrySet()) {
                    String strColumnName = entry.getKey().toString();
                    String strValue = cellIterator.next().toString();
                    rowMap.put(strColumnName, strValue);
                }
            }
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data.iterator();
    }

    private static Map<String, String> getColumnNames(Row row) {
        Map<String, String> columnNamesMap = new LinkedHashMap();
        Iterator<Cell> cells = row.cellIterator();
        while (cells.hasNext()) {
            String strColumnName = cells.next().toString();
            columnNamesMap.put(strColumnName, strColumnName);
        }
        return columnNamesMap;
    }
DataProvider.Class
@DataProvider(name = "AmazonProduct", parallel = false)
        public static Iterator<Object[]> getDeviceName() {
            String strWorkBookPath = new StringBuilder().append(System.getProperty("user.dir")).append(File.separator)
                    .append("resources\\testdata").append(File.separator).append("testdata").append(".xlsx").toString();

            Iterator<Object[]> testData = ExcelUtil.getTestData(strWorkBookPath, "Mobiles");
            return testData;
        }
TestScripts.java
@Test(dataProvider = "AmazonProduct", dataProviderClass = DataProviderUtil.staticProviderClass.class)
public void searchAmazonProducts(Map<String, String> dataMap) {
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get("https://www.amazon.in/");
        wait = new WebDriverWait(driver, 25);
        WebElement txtSearchEngine = wait.until(ExpectedConditions.visibilityOfElementLocated(
                By.cssSelector("#twotabsearchtextbox")));
        System.out.println("\n Devices : " + dataMap.get("Devices"));

        txtSearchEngine.sendKeys(dataMap.get("Devices"));
        txtSearchEngine.submit();
        driver.quit();
    }

Please refer to the below image,

Data provider in Excel Workbook

Parameterization in TestNG:

When there is a need to perform tests by using different test data, or when you are looking to test by logging in with a different user that has distinct usernames and passwords then Parameterization will come in handy as the “@Parameters” annotation in TestNG allows argument values to pass to Test methods via the testng.xml file. (Parameter values are declared in testng.xml) We have explained the different user scenarios using an example.

Syntax:

@Parameters({ “param-name” })

Let’s write a simple program for the @Parameters annotation,

Code:

@Test
@Parameters({"Username"})		
public void TestMethod1(String strUsername) {	
//We can retrieve the data using this argument. (It’ll retrieve from testng.xml file)
System.out.println("\n Username : " + strUsername);
}

Parameterization in TestNG

TestNG Tutorial for Parallel Execution:

Saving time during the testing process is always a priority, and one of the best possible ways to do it would be by executing tests in parallel rather than sequential execution. So as promised at the beginning of this TestNG Tutorial, let’s see how we can have test suites executed in parallel on different browsers, and how it can be even defined in the Testing.xml file.

TestNG provides different levels of execution that we can achieve by using the Testing.xml file. The attributes that we can use to achieve them are,

i. Methods,

ii. Classes, and

iii. Tests.

i. parallel=”methods”:

We had already seen about methods that are dependent on other methods for their execution, so accordingly if you are looking to execute many independent methods in parallel, then this attribute can be used. Using this attribute, all test methods will run on a separate thread. In the below example, we have executed two test methods in two threads.

Note: Thread count is the specified number of browser instances that should be assigned for this test execution.

Syntax:

<suite name="Test-method Suite" parallel="methods" thread-count="2" >

Parallel Methods

Code :

TestParallelForMethodsExecution.java
public class TestParallelForMethodsExecution {

    @Test
    public void visitCodoidPage() {
        String baseUrl = "https://codoid.com/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        WebDriverWait wait = new WebDriverWait(driver, 25);
        String testTitle = "QA Testing Company - Software Testing Services";
        boolean isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
        WebElement elmntAboutUsTab = driver.findElement(By.xpath("//ul[@id='top-menu']/li/a[text()='About Us']"));
        elmntAboutUsTab.click();
        driver.close();
    }

    @Test
    public void visitAmazonPage() {
        String baseUrl = "https://www.amazon.in/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        WebDriverWait wait = new WebDriverWait(driver, 25);
        String testTitle = "Online Shopping site in India";
        boolean isVerified;
        isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
        driver.close();
    }
}
TestNG.xml
<suite thread-count="2" name="Parallel-Test-Suite" parallel="methods">
    <test name="To Run TestNG :: Parallel methods concept">
        <classes>
            <class name="scripts.TestParallelForMethodsExecution"/>
        </classes>
    </test>
</suite>
ii. parallel=”tests”:

But the problem is that the above type will not work if we have a lot of test methods that are dependent on each other like how we saw earlier with the email example. So this attribute can be used to overcome this issue by adding all the dependent tests to a suite file (Testing.xml) and executing it separately in a thread as each tag will be considered a test suite and it’ll be executed in a separate thread.

Syntax:

<suite name="Test-Suite" parallel="tests" thread-count="2">

Parallel Test

Code

MultipleSession1.java
public class MultipleSession1 {

    public static WebDriver driver = null;
    public static WebDriverWait wait = null;

    @Test
    public void visitAmazonPage() {
        String baseUrl = "https://www.amazon.in/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 25);
        String testTitle = "Online Shopping site in India";
        boolean isVerified;
        isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
    }

    @BeforeMethod
    public void beforeMethod() {
        System.out.println("\n Starting Test On Chrome Browser");
    }

    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }
}
MultipleSession2.java
public class MultipleSession2 {

    public static WebDriver driver = null;
    public static WebDriverWait wait = null;


    @Test
    public void visitCodoidAboutUsPage() {
        String baseUrl = "https://codoid.com/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 25);
        String testTitle = "QA Testing Company - Software Testing Services";
        boolean isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
        WebElement elmntAboutUsTab = driver.findElement(By.xpath("//ul[@id='top-menu']/li/a[text()='About Us']"));
        elmntAboutUsTab.click();
    }


    @BeforeMethod
    public void beforeMethod() {
        System.out.println("\n Starting Test On Chrome Browser");
    }

    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }
}
TestNG.xml
<suite thread-count="2" name="Parallel-Test-Suite" parallel="tests">
    <test name="To Run TestNG :: Parallel Tests concept - 1">
        <classes>
            <class name="scripts.MultipleSession1"/>
        </classes>
    </test>
    <test name="To Run TestNG :: Parallel Tests concept - 2">
        <classes>
            <class name="scripts.MultipleSession2"/>
        </classes>
    </test>
</suite>
iii. parallel=”classes”:

This type has similar usage scope as the previous one with one major difference. Using this attribute, we can execute tests under each class in an individual thread, and the same has been explained in the below example.

Syntax:

<suite thread-count=”2” name =”Parallel-Test-Suite” parallel=”classes”>

Parallel Classes

Code:

Test1.java
public class Test1 {

    public static WebDriver driver = null;
    public static WebDriverWait wait = null;

    @Test
    public void Test1() {
        String baseUrl = "https://codoid.com/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");
        driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 25);
    }

    @Test
    public void Test2() {
        String testTitle = "QA Testing Company - Software Testing Services";
        boolean isVerified;
        isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
    }
    @Test
    public void Test3() throws InterruptedException {
        WebElement elmntAboutUsTab = driver.findElement(By.xpath("//ul[@id='top-menu']/li/a[text()='About Us']"));
        elmntAboutUsTab.click();
    }
    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }
 }
Test2.java
public class Test2 {

    public static WebDriver driver = null;
    public static WebDriverWait wait = null;


    @Test(priority = 1)
    public void launchAmazonURL() {
        String baseUrl = "https://www.amazon.in/";
        System.setProperty("webdriver.chrome.driver", "./resources/drivers/chromedriver.exe");

        driver = new ChromeDriver();
        driver.get(baseUrl);
        driver.manage().window().maximize();
        wait = new WebDriverWait(driver, 25);

    }

    @Test(priority = 2)
    public void verifyAmazonTitle() {
        String testTitle = "Online Shopping site in India";
        boolean isVerified;
        isVerified = wait.until(ExpectedConditions.titleContains(testTitle));
        Assert.assertTrue(isVerified);
    }

    @Test(priority = 3)
    public void navigatesToAboutUsPage() throws InterruptedException {
        WebElement elmntAmazonPayTab = driver.findElement(By.xpath("//a[text()='Amazon Pay']"));
        elmntAmazonPayTab.click();
    }

    @BeforeMethod
    public void beforeMethod() {
        System.out.println("\n Starting Test On Chrome Browser");
    }

    @AfterTest
    public void terminateBrowser() {
        driver.close();
    }
}
TestNG.xml
<suite thread-count="2" name="Parallel-Test-Suite" parallel="classes">
    <test name="Using Classes attributes for parallel execution.">
        <classes>
            <class name="scripts.Test1"/>
            <class name="scripts.Test2"/>
        </classes>
    </test>
</suite>

In the above 3 points, it can be seen that we have defined the keywords for parallel (classes, tests, and methods) attributes on the Testing.xml file. Now, we’re going to explain the sample scripts for classes and methods.

Conclusion:

As promised at the beginning of this TestNG tutorial, we have explored all the plus points of TestNG. So we hope this information would be useful and that you have enjoyed reading this blog. As one of the leading automation testing companies, we have always found TestNG beneficial in crucial circumstances, and hope it will come in handy for you as well.

4 Test Automation Mistakes the Every QA Team Should Avoid

4 Test Automation Mistakes the Every QA Team Should Avoid

In the world of software development, no product could ever face success without undergoing thorough and rigorous testing. Test automation is essential as it ensures that the end product delivered is stable and works according to the required specifications. However, QA teams and automation testing companies are not immune to making mistakes. In fact, any mistakes they made could potentially cost time, money, and trust that could easily derail the product’s success. Here are four common test automation mistakes your team should avoid at all times.

Not Identifying What Should and Shouldn’t Be Automated

For a tester, understanding what areas to automate and how it will help the organization is the basic rule of thumb for test automation success. It’s why you do the things you do. 

However, there are times when you might be tempted to jump in and start hunting for tools to do the job. Don’t be too hasty about it, and make sure to clearly identify first which tasks to automate and which ones to execute manually. This will effectively be your guiding principle throughout the testing process. Failure to do so is a recipe for disaster.

Automating the Wrong Things

In a way, this is the result of mistake number one. Because you failed to identify what areas to automate, you risk making mistakes and automating the wrong things. Many teams try to automate tasks that aren’t actually good candidates for automation. One big miscalculation in this area is trying to translate your existing testing activities one-to-one into automation. Doing this is a huge waste of time and effort, leaving you to focus on things that don’t need to be automated at all. Keep your priorities straight, and don’t forget why you’re doing the testing in the first place.

Picking the Wrong Tools

There are many different problems you want to solve with automation, and one tool can’t solve all of them. That’s why picking the right tools is essential. The thing is, a lot of QA managers and automation testing companies are always looking for that one tool that could solve everything for them. The truth is, it just doesn’t exist.

The key is finding out what problem you want to solve with a tool, rather than buying a tool and then finding a problem for it. It’s best to design specific problems you need to solve before shopping around for a tool.

Failure to Coordinate with Fellow Testers

There are many people involved in a testing team. All these people are equipped with a different skill set that can prove invaluable to you. While they have their own specializations, that doesn’t mean you don’t discuss the progress of your tasks with them. Coordination is key to accelerating product delivery. Without coordination, you risk committing more mistakes and taking more time to fix those mistakes. If everyone is on the same page, they can respond better if something doesn’t go according to plan.

Conclusion

When handling an automation testing project, you need to be mindful of every little detail, including avoiding any pitfalls such as the ones mentioned above. While it is good to learn from your mistakes, it is always better to be preventive, especially if we’re talking about developing software.

If you’re in need of a QA company with a seamless track record, Codoid is your best choice. Every new software product deserves high-quality automation testing, and our team happens to be fully equipped to do just that. When it comes to QA automation services, there’s no better choice than Codoid. Partner with us today!

5 Mobile App Testing Mistakes to Avoid When Creating Your App

5 Mobile App Testing Mistakes to Avoid When Creating Your App

Mobile apps have taken the world by storm over the last decade. These powerful programs have allowed users to perform various tasks on their smartphones, such as paying their bills, guiding them through traffic, and even purchasing groceries. However, with so many apps on various marketplaces, it’s become even more difficult to design and launch an app successfully. 

Even though you may have a unique, potentially groundbreaking idea for an app, you’ll need to subject it to rigorous mobile app testing services to make sure it works properly in all intended scenarios before rolling it out. Otherwise, any issue that pops up can cause your intended users to drop the app altogether.

Here are five mobile app testing mistakes to avoid:

1. Failing to Test on Actual Devices

Many companies prefer to use cloud-based tools when testing the application in the interest of time and resources. While these tools are efficient in supporting the actual device, they cannot replace them entirely. It is crucial to test your mobile app on a real device as some features and functionalities present differently on the cloud than on the device itself. Be sure to test in at least two real devices, like Android and iOS, along with the last two versions of the operating systems.

2. Not Doing Proper Responsive Testing

Responsive testing is another critical aspect that many companies tend to skip. However, it is essential to check the applications and render them in multiple devices of various screen sizes and operating systems. It’s best to entrust this to mobile testing service providers, as they have all the tools and equipment necessary to test an application’s render throughout various devices.

3. Forgetting to Consider Device Configuration and Network

Suppose your app needs a precise amount of storage space or Internet connection to work properly. In that case, you’ll need to consider the device configuration and network when testing, another part that companies forget to do. Test your app with different RAM sizes and evaluate the application’s speed, which will help you determine the optimal conditions for your app to function. You’ll also need to conduct network virtualization testing to check your app’s performance with various internet speeds, data, and others.

4. Testing Only at the End

Testing your mobile app must be done right from the beginning, not at the end. That way, you can guarantee that your mobile app is stable and performs as such, and the team has enough time to resolve the issues instead of rushing the solution to meet deadlines. Rushed work often means cutting corners in the process, which you definitely don’t want in your app.

5. Being Unable to Recreate User Usage

Users have very high expectations of mobile apps and expect them to look attractive, perform well, and have an intuitive interface. User experience (UX) ultimately makes or breaks an app, so it’s crucial to test your app from their perspective and recreate how they use your app. It must perform according to your user’s expectations and not simply what you expect it to do. 

Conclusion

Apps have come a long way since their early days, and they continue to grow more advanced and sophisticated. As such, for your app to succeed, you must subject it to thorough testing before rolling it out. Providing a seamless experience for your users is the key to getting them to use it frequently, which will earn you a rapidly expanding user base.

If you’re looking for mobile app testing services to ensure your app is fit to launch, let us know at Codoid! As part of the leading test automation companies, our grade-A testing will give your growing product all the care and attention it needs to fulfill its potential. Contact us today to get started on testing your app!

The Best JavaScript Testing Frameworks you should be using in 2021

The Best JavaScript Testing Frameworks you should be using in 2021

Automation testing using JavaScript has been gaining popularity in recent days making a blog about the best JavaScript Testing Frameworks available the need of the hour. A conversation between business analysts, developers, and testers about a feature will become specifications. After that, the developers & testers convert the specs into automated acceptance tests. Automated tests help the team to drive the feature development as passing acceptance tests prove the fact that the agreed feature has been developed as expected.

To convert specifications into automated acceptance tests, devs & QAs should use the same programming language. Let’s say your team is using JavaScript for development and Java for automation testing. In this case, you won’t be able to enable effective collaboration between the developers & testers which is a big concern. Analysts & developers can capture acceptance criteria effectively. However, testers are good at adding edge cases making them invaluable as well. That is why everyone’s involvement right from the beginning is vital with common tools, frameworks, and language.

In this blog article, we have listed the best JavaScript Testing Frameworks which are widely used for writing unit tests and acceptance tests.

Jasmine

When developers focus more on components than features, they don’t add value to the business. Writing tests in plain English helps your team focus on the business goals and Jasmine is one of the best testing frameworks to make it possible. Using Jasmine you can write meaningful tests which can be understood by everyone in the team and help the developers to write higher quality code more efficiently.

Jasmine has support for Node.JS, RUBY, and Python. If you want to run the tests on a Web Browser instead of running them in interpreter/programming engine, then you can go for Jasmine Standalone. Now let’s find out how to use Jasmine in Node.JS beginning right from its installation.

Installation:

To install Jasmine, run the below npm command.

npm install jasmine —save-dev
Initialization

To set up Jasmine in a Node.JS project, you need spec files and jasmine.json (Configuration file). You can add these files manually. However, we have an npx command to initialize Jasmine in your project and it has been listed below

npx jasmine init

After running the above command, you can find the ‘spec’ folder and ‘jasmine.json’ file under the spec->support folder.

Add Jasmine in package.json

Now, you need to inform your node project that you are using Jasmine for testing. Open package.json and update the ‘test’ value as ‘jasmine’ as shown below.

{
  "name": "jasmine-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jasmine"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jasmine": "^3.7.0"
  }
}
Describe

In order to group related test cases like how we group scenarios in a feature file in Cucumber, you need to create a JavaScript file and write a ‘describe’ function as shown below.

describe("User Management", ()=>{

})

In the above function, it is a placeholder to add ‘User Management’ related test cases.

Specs

Specs are your test cases. You need to write specs inside the ‘describe’ function as shown below.

describe("User Management", ()=>{

    it("should signup",()=>{

    })

    it("should login", ()=>{

    })
})

As we mentioned earlier, everyone in the team should understand what is the purpose of each test. When naming a test case for unit & acceptance tests, you need to describe what you are expecting. However, it is a cumbersome task for a developer to focus on names. If there are a rule and a standard which come from the testing framework, then the team members will be able to stick to the business goals and focus on achieving them instead of concentrating only on the code components.

That is why the Jasmine framework has the ‘it’ function and the first argument starts with ‘should’. When a test case says ‘It should do something’, the developer will focus on that something throughout the development which is exactly what we want.

How is a spec pass or fail determined? You can have multiple assertion lines inside a spec and even if one of those assertions fails, the spec will be marked as ‘Fail’.

Assertions

Jasmine has an in-built assertion function which is called ‘expect’. Expect function has one argument which takes the actual value. You can also chain the assertion using Matcher functions.

expect(“my string”).toMatch(/string$/) – Expect the actual value to match a regular expression.

expect(bigObject).toEqual( “foo”: ‘bar’, ‘baz’ ) – Expect the actual value to be equal to the expected value using deep equality comparison.

expect(thing).toBe(realThing) – Expect the actual value to be === to the expected value.

Configurations

Jasmine has a total of five configurations in the jasmine.json file. Let’s take a look at the purpose of each of these configurations one by one.

“specdir” – A directory path where you have the specs in the current project directory.

“specfiles” – You can include & exclude spec file paths with regular expression.

“helpers” – Before the test execution commences, you may need some supporting files that should be executed. The helpers config is the placeholder to mention the supporting JS files.

“stopSpecOnExpectationFailure” – This is a boolean config. If the value is true, then the spec execution will be stopped when the first assertion is failed.

“random” – Run the specs in random order.

Advantages of Jasmine
  • You can customize the Jasmine report.
  • It has a very strong community that supports the users.
  • You can even create your own Matchers.
  • It is extremely simple and easy to use making it the choice of many developers and testers mainly for its simplicity.

Jest

Jest is also a popular JavaScript Testing framework that works with Node.JS, React, Angular, Vue, Babel, TypeScript, and more. Jest was developed by Facebook and so it runs thousands of tests for Facebook on a daily basis. Apart from Facebook, there are many other prominent companies that also use Jest. So let’s see what makes Jest one of the best JavaScript Testing Frameworks and how you can implement it in your project. Let’s begin with its installation process.

Installation

You can easily install Jest by making use of the below code,

npm install --save-dev jest
Add Jasmine in package.json

Update scripts>test node as ‘jest’ in Package.json as shown below.

{
  "name": "jest-sample",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^26.6.3"
  }
}
Configuration

No configuration is required to write or run Jest tests. However, every testing framework has its own configuration file. To create a config file, you can run the below command.

npx jest —init

Once you run the above command, Jest will ask you a few questions to create the config file.

Migrating from Jasmine to Jest

If you are planning to migrate from Jasmine to Jest, then we’ve got some good news for you as Jest is compatible with Jasmine tests. This makes the migration far less complicated. However, if you want to do a code-level migration, you can use third-party jest-codemods for the best results.

Assertions

In order to write assertions elegantly in a test, you would definitely need sophisticated Matchers. Jest has a lot of compressive matchers that you could use. However, we have listed some of the commonly used Matchers below.

test('two plus two is four', () => {
  expect(2 + 2).toBe(4);
});
test('object assignment', () => {
  const data = {one: 1};
  data['two'] = 2;
  expect(data).toEqual({one: 1, two: 2});
});
test('null', () => {
  const n = null;
  expect(n).toBeNull();
  expect(n).toBeDefined();
  expect(n).not.toBeUndefined();
  expect(n).not.toBeTruthy();
  expect(n).toBeFalsy();
});
Snapshot Testing

Your Acceptance Tests test the application under test by performing actions on the UI. However, it never validates whether the UI is rendered as same as before and if the CSS styles are applied correctly or not. Jest has a feature to address this issue (i.e. Visual Regression Testing). Using Jest, you can capture snapshots and compare them with the expected snapshot thereby creating a huge advantage if that is your primary need.

Advantages

If you want to run your tests in parallel, then Jest is your go-to testing framework. Jest has numerous assertion functions. In terms of ease of adoption, simplicity, support, and documentation, Jest is hands down the clear winner.

Mocha

Mocha is a JavaScript Testing framework only for Nod.JS. Mocha doesn’t have an in-built assertion library. However, it allows you to use the following libraries such as should.js, chai, expect.js, better-assert, and unexpected for assertions. You can execute tests in two modes (Serial & Parallel).

Conclusion

Jest and Jasmine are the best JavaScript Testing frameworks. However, most of the engineers are comfortable with Jasmine over Jest. As an automation testing company, we use Jasmine for Protractor automation testing. Jasmine is the default testing framework for Protractor. Our suggestion is not final and it shouldn’t influence your framework decision.

Jest has many sophisticated features such as Configuring Visual Testing (i.e. Snapshot Testing) which is not as easy to do in Jasmine. However, in Jest, it is pretty straightforward. Apart from that, test creation and assertions are similar in both these frameworks. If you feel Jest is suitable for your project, please go ahead.