Jest Tutorial For Selenium JavaScript Testing With Examples

Posted by Harshit Paul | April 2, 2020
JavaScript • Selenium Testing • Selenium Tutorial •

105499 Views | 16 Min Read

Jest Tutorial

As a developer, I know for a fact that I have to constantly brush up myself with new updates. This means that not only I have to keep learning more about the frameworks and language I work with. But also to look for new frameworks that gives me an edge over others. One such survey that I am always looking forward to as a developer is the ‘StateofJS’. It is revered by all the JavaScript developers as a key source of information. ‘StateofJS’ provides key insights on the major trends in front-end, back-end, testing, etc. As per StateofJS 2019, Jest has been the most interesting and satisfying framework for JavaScript testing.

key-insights

Being a fan of Selenium test automation, I was curious to get my hands on Jest for Selenium JavaScript testing. I wanted to quickly validate my recent code changes and Jest was a big help in reducing my unit testing efforts. Which is why I thought of sharing what I learned with you, so you can go ahead and automate your unit test cycles.

In this Jest testing tutorial, I am going to help you execute Selenium JavaScript testing through the Jest framework. We will start off with basics to Jest, its advantages, and then we will hop over to the practical demonstration where we will execute our first Selenium test automation script for Jest and get our hands dirty on this framework.

What Is Jest?

Developed by Facebook, Jest is an open-source testing framework built on JavaScript, designed majorly to React and React Native based web applications. We generally observe that unit tests for the frontend layer are not much suitable as it requires a lot more configuration to be done which can be complex at times. This complexity can be reduced to a great extent with the Jest framework.

Moreover, Jest can be used to validate almost everything around JavaScript, especially the browser rendering of your web-applications. Jest is a preferred framework for automated browser testing too and this makes it one of the most popular and renowned Javascript testing libraries framework!!

Jest also provides an excellent blended package of an assertion library along with a test runner and a built-in mocking library. The feature that makes it stand out is it’s simplicity and that is what makes it compatible to test any JavaScript Library Projects such as AngularJS, Vue JS, Node JS, Babel and TypeScript.

Another great feature that it offers is snapshot testing, which basically helps us to get a test of the delta changes of the web-applications that are transformed after a particular time. Additionally, Jest also has a built-in support for code coverage which can generate reports to figure out the areas or the part of the code that is not covered as a part of the test execution. Now that we’ve covered what is Jest in this Jest tutorial, let’s explore why you should use Jest for Selenium test automation.

Why to Use Jest For Selenium JavaScript Testing?

In the world of Selenium JavaScript testing, there are many automated frameworks that are used for cross browser testing. So why Jest? Well, here are a few killer points that make Jest better than other test frameworks. Some of them are:

  • Speed and Performance – Jest framework is fast when it comes to executing the test cases. Not only it boosts up the entire test suite, but it also offers great efficiency in the watch mode that can be enabled in this framework.
  • automation-trial-now

  • Pre-commit hooks – Jest framework offers pre-commits hooks which are basically the ability to execute only those sets of test cases that are significant in the current run or the ones that are changed after the previous commit. That way, we don’t have to wait for the execution of all other test cases. These tests are popularly known as Snapshot testing & are useful in reducing the regressions testing efforts.
  • Complete Package – The framework comes with more or less with all the required features. These built-in modules provide good support for plugins and there is no need to download any other third party executable like mocha or cucumber etc. to perform certain activities. In case, if we require to add any other library with the Jest framework, they are easily configurable, and we can choose which module to include so that there are no issues with compatibility.
  • Easy to Migrate – Any current test project can easily be migrated and switched to use the Jest framework programmatically without any issue or code interaction with the use of code mods module.
  • Added Features and Configurations – The framework is not just an ordinary and basic test runner but on the other hand it also offers some of the advanced features such as ability to auto mock modules, setup coverage thresholds, module mappers. This includes the support from multiple projects in the same runner and customer resolvers such as babel and webpack.

Other than the ones listed above, here are some pros of using Jest framework by the StateofJS survey.

StateofJS

I’m Jest Getting Started! – Installation, Configuration, and Prerequisites

Before I start with, how to write our first Selenium test automation script with Jest. There are certain basic prerequisites and installations to get started with this Jest testing tutorial for Selenium JavaScript Testing. Below are some of the libraries and packages required to be installed on the system in order to run Jest test scripts.

  • Node JS and Node Package Manager (npm) : Node JS can be installed either using the npm manager: nodejs.org/en/download/package-manager or directly using the Windows Installer binary from the nodejs.org web site here.
  • Selenium Web Driver: The Selenium web driver is required as a dependency for the Jest Module and should be installed in the root directory. The latest version of the selenium web driver can installed using the npm command as shown below:
  • Jest Package Module : Now by using the node package manager installation of the required Jest module packages can be done.
  • To install the latest version navigate to the npm command line tool, and initialize the npm using the below command :

    Then, install the Jest module using npm using the below commands.

    ‘-g’ : It indicates the npm to install the module globally, and allows us to access and use the module like a command line tool and does not limit its use to the current project.

    ‘--save-dev’ It indicates the npm to place the Jest executable in the bin folder of the root directory i.e. ./node_modules/.bin folder

    You will now be able to run the commands in our command line using the Jest keyword.

  • Java – SDK: Since Jest is a Selenium test framework and Selenium is built upon Java ,and so there is also a need to get the installation done for the Java Development Kit ( preferably JDK 7.0 or above ) on the system and then configure the system with the JAVA environment.
  • Browser Driver: This npm command installs the suitable driver required to trigger the browser and place the executable inside the root directory.

Now that you’ve set up and completed all the requirements in this Jest testing tutorial, let’s move on to how to run your first Selenium test automation script for Javascript testing.

Running Your First Jest Script For Selenium JavaScript Testing

After the initial setup and configurations are done, let’s write our first Jest script for Selenium JavaScript testing. I’ll will start by creating the project and naming the directory as jest_test and initialize the test project by navigating to the directory through the command line and executing the command

This will create a base package.json file will all the basic project configuration which will be referenced in our test scripts. Finally, I’ll create a subfolder inside it that will contain our test script name single_test.js. Our initial project hierarchy will look like this:

Now, let’s have a look at all the files, their content and their purpose in the project, you may copy paste the content into your local project files.

This file contains all the project configuration and dependencies required during project setup. The definitions from this file are used for executing the script.

This file contains all the scripts related features and behaviour that are expected in our application. These configurations are internally referenced in the script to implement the required functionality. It offers a lot more features like mocking, coverage, report etc and you are free to turn on and off the features as and when required.

This is our Jest test script that we will be executing. In this test we will launch a web page and execute certain scenarios.

It is important to check whether the below section is present in our package.json file as this contains the configurations of our test script and hence will be required to execute the tests.

Now, finally, we can run our test in the command line and execute from the base directory of the project using the below command:

The output of the above test is :

output3

Code Coverage

Now you can test code coverage report using the inbuilt coverage plugin by executing the command.

Executing this command will generate a detailed report of us for the test case.

Delta Testing and Group Testing With Jest Framework

Let us look at some of the important keywords that you should be aware of when writing our Selenium test automation scripts and performing tests in the Test Driven Development (TDD) environment and then I will explain how we can use them in our tests.

  • expect: expect helps us verify that the values we specified in our tests meet the conditions specified i.e. a value you would like to check against the value that you were expecting. This can be done with the help of various matchers that are available to validate different combinations of things as per the requirement. Some of the matchers that we can use with expect function in Jest are : .toBe() , toBeA() , toContain() , toEqual() ,toContainEqual() etc.
  • test: It provides what a function should perform and lets us test a unit of the function. For Example: test(‘whether a particular attribute is present in the input’) etc.

Delta Testing

With Jest, you can also execute delta testing by running tests in watch mode. This will execute the tests automatically whenever there is a change in code encountered. The watch mode monitors the application for any changes. I will execute our previous tests with the watch mode on and see if it throws an error when the test fails.

For this, we need to execute the command with the --watchAll parameter in the command line

Group Tests

Let us extend our test further and group our multiple tests to create a test suite. In Jest, multiple tests are grouped into units and are distinguished with the describe() function. It helps by grouping several related tests together.

In the last example, we have performed the automated browser testing by launching a website and performing certain scenarios on them. Here we will also test check whether the input is an anagram. For this, we introduce a new function checkAnagram(). This will constitute the first module. (module1-utils.js) In the other module we will test for positive , negative and sum of the values. This will be our second module (module2-utils.js).

So, we will have our directory structure like below, where we will be executing the group test which will internally refer to the module1-utils and module2-utils.

Finally, we will be executing the test script using the command

Output:

output2

We can see that we have executed the group of tests in the form of test suites which are internally executing multiple other test cases as we have described using the describe function.

Scalability Issues With Running Selenium Automation On Local Infrastructure

Now in this Jest testing tutorial, we’ll see the scalability issues that might rise by running your selenium test automation scripts on your local setup. You can install Selenium WebDriver in your local systems and can proceed with the execution of automated test cases. However, there are certain drawbacks of using Selenium Grid in a local setup.

  • First, since it is in our local workspace, it requires us to manage and set up the underlying infrastructure required for the test, we cannot focus much on our testing strategy.
  • The initial setup of the Selenium Grid can be tedious especially when there is a need for multiple node servers. There can be issues with the performance majorly when parallel group tests are about to be executed.
  • Also, when performing cross browser testing our local system may not be equipped with all the different versions of browsers installed.
  • The same limitation arises when dealing with operating systems as some applications might be specifically designed for a particular operating system and hence requires a specific environment to run.

Choosing Cloud based Selenium Grid over Local Setup

Moving ahead with our Jest testing tutorial, we need to figure out a way for this limitation , this is where the online Selenium Grid plays a vital role and comes to the rescue. By performing parallel testing on Cloud based Selenium Grid there is no need to install and manage unnecessary virtual machines and browsers for Automated Cross browser Testing. It provides real browsers running with all major operating systems running. Further, it also helps reduce our test cycles and hence boost our market ready delivery.

Since LambdaTest also provides integration with Jest, we will look at how to run our test script on its cloud platform. In order to start executing automated testing for our application, we would just need good Internet connectivity and a simple and free sign up on the LambdaTest platform.

Executing Jest Script Using Cloud Selenium WebDriver On The Cloud Based Selenium Grid Lambda Test

Now that you have an idea about various offerings of the cloud grid in terms of boost in productivity, log analysis and wider test coverage. I’ll now execute a sample test script on the online Selenium cloud grid platform offered by LambdaTest for a better understanding. The process is pretty straightforward and it just needs a few additions in configurations, which will allow our script to connect to the Cloud platform.

To get started we would require generating a capability matrix that allows us to choose from various combinations of environments available and specify the environment we would like to run our tests on.

Here is the link to visit Lambdatest selenium Desired Capabilities Generator

desired-capabilities-generator

So, in our case the capabilities class will look similar as below:

Next and the most vital thing for us is to get our access key token which is basically a private key to connect to the platform and execute automated tests on Lambda Test. This access key is unique for every user and it can be fetched and regenerated from the individual user profile section of the user account as shown below.

access-key

Alternatively, the access key, username and hub details can also be fetched from the Automation Dashboard as shown in the image screenshot below.

automation-dashboard

Executing Our First Script on Cloud Setup

Here, our script will connect us to the LambdaTest platform, and I will be executing our test on the chrome browser. In this test case, I will open the LambdaTest website to perform certain operations on it such as validating the content , taking a screenshot etc. So, our directory structure will be pretty simple as below:

Now since our test scripts are ready to be executed in the cloud grid , the final thing that we are required to do is to run the tests from the base project directory using the below command:

This command will validate the test cases and execute our test suite across all the test groups that we have defined.

Below is the output on the command line:

Output:

output

Now, if I open the Lambda Test platform and navigate to the automation dashboard you can see that the user interface shows that the test ran successfully and passed with positive results.Below is the sample screenshot

screenshot

You must be aware now that you can fast track our automated browser testing process for Jest by executing these test cases on an Online Selenium Grid. Some of the best features provided by it are the parallel testing environment, support for programming and coding languages like Java, Python , C etc. along with the test frameworks that are supported with Selenium and allow easy integrations with all the famous CI/CD platforms and the Desired Capabilities which prove to be efficient in complex use cases. I’d encourage you to execute your first Jest Script both locally and on the cloud Selenium platform.

Also Read:Mocha JavaScript Tutorial With Examples For Selenium Testing

Wrapping It Up!

Now that you know that Jest is a quick testing framework and is also easy to set up and doesn’t have many complexities. Jest framework is actively used by many organizations to test applications as it is simple to migrate from other testing platforms and provides an all in one package with TypeScript support. The test outcome and the consequences can at once accessed from the command line interface.

Also, the user interface offered by this platform is very interactive and we can leverage the various benefits of Selenium test automation testing both as a beginner and an expert. Hence, it’s a good idea to migrate our Selenium automation tests to cloud infrastructure and increase our test coverage and also cut down on test execution time. This is all we need to know to run our Jest test scripts.

Great! This concludes our Jest testing tutorial and now i hope you are well versed with the Jest framework. But as i just said, this is ‘jest’ a beginning and there’s a lot more to come. There is a lot more still to be learned, and I’d be happy to guide you along the way. Hit on the bell icon, and you’d get alerts to all our upcoming tutorials. Meanwhile, you can read our other tutorials on Nightwatch.js, Cucumber.js and Mocha. Happy testing!

cross_browser_testing_tool

Written by Harshit Paul

Harshit works as a product growth specialist at LambdaTest. He is also an experienced IT professional, who loves to share his thoughts about the latest tech trends as an enthusiast tech blogger.

Related Articles

Best Reporting Tool For Selenium

9 Of The Best Reporting Tools For Selenium

14747 Views | 16 Min Min Read

Element In Selenium

How To Get Text Of An Element In Selenium?

92904 Views | 7 Min Min Read

Leave a Reply

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