Jest Testing with Selenium and JavaScript: Beginner’s Guide
Harshit Paul
Posted On: April 2, 2020
152955 Views
17 Min Read
This article is a part of our Content Hub. For more in-depth resources, check out our content hub on Selenium JavaScript 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.
Being a fan of Selenium test automation, I was curious to get my hands on Jest testing framework JavaScript automation testing. I wanted to quickly validate my recent code changes and Jest testing framework 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 testing 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.
Now run Jest testing scripts in parallel faster than any other automation testing grid on LambdaTest’s online grid. If you are preparing for an interview you can learn more through Jest Interview Questions.
What Is Jest Testing Framework?
Developed by Facebook, Jest is an open-source testing framework built on JavaScript, designed majorly to test 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 testing framework.
Moreover, Jest testing framework 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 testing tutorial, let’s explore why you should use Jest for automation testing.
Why to Use Jest Testing Framework?
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 testing better than other test frameworks. Some of them are:
- Speed and Performance – Jest testing 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.
- Pre-commit hooks – Jest testing 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 testing 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 testing 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 testing framework by the StateofJS survey.
Jest Testing 101 – 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 testing 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.
- Java – SDK: Since Jest testing framework uses components of Selenium, which 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.
1 |
$ npm install selenium-webdriver |
To install the latest version navigate to the npm command line tool, and initialize the npm using the below command :
1 |
$ npm init --y |
Then, install the Jest module using npm using the below commands.
1 2 |
$ npm install -g Jest $ npm install --save-dev jest |
‘-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
1 |
$ npm install --save-dev jest |
You will now be able to run the commands in our command line using the Jest keyword.
1 |
$ npm install -g chromedriver |
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.
You can take this certification as proof of expertise in the field of test automation with JavaScript to empower yourself and boost your career.
Here’s a short glimpse of the Selenium JavaScript 101 certification from LambdaTest:
Running Your First Jest Testing Script using Selenium and JavaScript
After the initial setup and configurations are done, let’s write our first Jest testing script. 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
1 |
$ npm init |
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 testing 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.
1 2 3 |
"scripts": { "test": "jest", }, |
Now, finally, we can run our test in the command line and execute from the base directory of the project using the below command:
1 |
$ npm test |
The output of the above test is :
Code Coverage
Now you can test code coverage report using the inbuilt coverage plugin by executing the command.
1 |
$ npm test --coverage |
Executing this command will generate a detailed report of us for the test case.
Delta Testing and Group Testing With Jest Testing 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
FAIL ./single_test.js ✕ executing test scenario on the website www.selenium.dev (15ms) ● executing test scenario on the website www.selenium.dev expect(received).toBe(expected) // check if the object is equal Expected value to be: true Received: false 6 | expect(search).toEqual('').toBe(true) 7 | expect(search).toEqual('').toBe(true) > 8 | expect(search).toEqual('').toBe(true) 9 | expect(search).toEqual('asa').toBe(false) 10 | }) 11 | at Object.<anonymous>.test (single_test.js:8:30) Test Suites: 1 failed, 1 total Tests: 1 failed, 1 total Snapshots: 0 total Time: 0.598s, estimated 1s Ran all test suites. Watch Usage: Press w to show more. |
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.
1 2 3 4 5 6 |
jest_test | -- test_scripts | -- module1-utils.js | -- module2-utils.js | -- group_test.js | -- package.json |
Finally, we will be executing the test script using the command
1 2 3 |
$ npm test or $ npm Jest groups_test.js |
Output:
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 Testing Scripts on a Cloud Based Selenium Grid like LambdaTest
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
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.
Alternatively, the access key, username and hub details can also be fetched from the Automation Dashboard as shown in the image screenshot below.
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:
1 2 3 4 5 |
jest_test | -- test_scripts | -- single_test.js | -- jest.config.js | -- package.json |
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:
1 |
$ npm test |
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:
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
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.Here’s a list of all browsers on LambdaTest automation testing platform that can be leveraged to run online Jest tests
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 testing 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!
Got Questions? Drop them on LambdaTest Community. Visit now