Jest Tutorial For Selenium JavaScript Testing With Examples
Tags: javascript, tutorial, selenium, automation
Published: 2020-05-11 09:11:23

---
title: Jest Tutorial For Selenium JavaScript Testing With Examples
published: true
description: This Jest tutorial for Selenium JavaScript testing will help you know more about what is Jest and how to run your first Jest Script and scale it with Selenium Grid.
tags: javascript, tutorial, selenium, automation
canonical_url: https://www.lambdatest.com/blog/jest-tutorial-for-selenium-javascript-testing-with-examples/
cover_image: https://www.lambdatest.com/blog/wp-content/uploads/2020/04/Jest-Tutorial.jpg
---

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](https://2019.stateofjs.com/testing/).

![key-insights](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/key-insights.png)

Being a fan of [Selenium test automation](https://www.lambdatest.com/selenium-automation?utm_source=dev&utm_medium=Blog&utm_campaign=Harshit-11052020&utm_term=Harshit), 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](https://www.lambdatest.com?utm_source=dev&utm_medium=Blog&utm_campaign=Harshit-11052020&utm_term=Harshit). 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.

- **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](https://2018.stateofjs.com/testing/jest).

![StateofJS](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/StateofJS.png)

## 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](http://www.nodejs.org/en/download/package-manager) or directly using the Windows Installer binary from the nodejs.org web site [here](https://nodejs.org/en/#home-downloadhead).
- **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:

 
```
$ npm install selenium-webdriver
```
 
 
- **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 :

```
$ npm init --y
```

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

```
$ 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

```
$ npm install --save-dev jest
```
 
 

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.

```
$ 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.

## 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

```
$ 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:

```
jest_test
        | -- test_scripts
                    | -- single_test.js
        | -- jest.config.js
        | -- package.json
```
 

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.**

```
//package.json-  Jest testing tutorial for Selenium JavaScript Testing
{
  "name": "Jest-Selenium-Webdriver-Test",
  "version": "0.1.0",
  "description": "Executing Our First Jest Automation Test Script with Selenium JavaScript Testing on Lambdatest",
  "keywords": [
    "javascript",
    "selenium",
    "tdd",
    "local",
    "test",
    "jest"
  ],
  
  "scripts": {
    "test": "jest"
  },
  
  "author": "rohit",
  "license": "MIT",
  "devDependencies": {
    "babel-eslint": "^10.0.1",
    "babel-jest": "^24.8.0",
    "babel-plugin-external-helpers": "^6.22.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "chromedriver": "^74.0.0",
    "eslint": "^5.16.0",
    "eslint-config-airbnb-base": "^13.1.0",
    "eslint-config-prettier": "^4.3.0",
    "eslint-plugin-import": "^2.17.3",
    "eslint-plugin-jest": "^22.6.4",
    "eslint-plugin-prettier": "^3.1.0",
    "jasmin": "0.0.2",
    "jasmine": "^3.4.0",
    "jest": "^24.8.0",
    "jest-environment-webdriver": "^0.2.0",
    "jsdom": "^15.1.1",
    "prettier": "^1.17.1",
    "rimraf": "^2.6.3",
    "selenium-webdriver": "^4.0.0-alpha.1"
  },
  
  "jest": {
    "setupTestFrameworkScriptFile": "./jest.config.js",
    "testEnvironment": "jest-environment-webdriver",
    "testEnvironmentOptions": {
      "browser": "chrome"
    }
  }
}
```
 

**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.**

```
//Jest testing tutorial for Selenium JavaScript Testing
// This configuration properties are taken from the official Jest documentation which is available at https://jestjs.io/docs/en/configuration.html 
//const {default} = require('jest-config');
module.exports = {
	// It indicates that each one imported modules in the tests must be mocked automatically
 	automock: false,
	// It indicates that it must prevent running the assessments after the primary failure is encountered
 	bail: false,
	// It indicates the "browser" field in package.Json when resolving modules
 	browser: false,
	// It indicates the listing where Jest must save the cached dependency details gathered from all throughout the tests
 	cacheDirectory: "/var/folders/jest_dx",
	// It suggests that the framework must automatically clean mock calls and instances between each test
	clearMocks: true,
	// It shows whether or not it have to have the coverage data collected while executing the test
 	collectCoverage: false,
	// It indicates that each one imported modules in the tests must be mocked automatically
// It indicates that an array of record extensions our modules should be using
 	moduleFileExtensions: [
   	"js",
   	"json",
   	"jsx",
   	"node"
 	],
	// It suggests the Jest to have an enum that specifies notification mode. Requires notify: true
 	notifyMode: "always",
	// It indicates the framework to have a preset this is used as a base for Jest's configuration
 	preset: null,
	// It suggests to run tests from one or extra projects
 	projects: null,
	// This indicates using the configuration to add custom newshounds to Jest
 	reporters: undefined,
	// This configuration shows the Jest to routinely reset mock state between every test
 	resetMocks: false,
	// This property suggests Jest to reset the module registry earlier than walking each person test
 	resetModules: false,
	// This configuration indicates Jest testing framework  to the course of a custom resolver
 	resolver: null,
     // This configuration indicates Jest to the course of a custom resolver
 	// This configuration indicates the Jest to allows us to apply a custom runner in preference to Jest's default inbuilt Jest test runner
 	runner: "jest-runner",
	// This configuration factors to the trails to modules that run a few code to configure or installation the test environment before each test run
 	setupFiles: [],
	// This configuration indicates the Jest to the direction to a module that runs some code to configure or installation the testing framework before than each test run 
 	setupFilesAfterEnv: null,
	// This configuration factors the Jest to the list of paths of the snapshot serializer modules that Jest must use for each of the snapshot testing
 	snapshotSerializers: [],
	// This configuration suggests the Jest to allow using a custom outcome or the result processor
 	testResultsProcessor: null,
	// This configuration shows the Jest to permit the usage of a new custom test runner instead of the default
 	testRunner: "jasmine2",
	// This configuration shows the Jest testing framework to assign the URL for the jsdom environment. It is shown in properties and configuration like the location.Href testURL: "http://localhost",
 	testURL: "http://localhost",
	// This property points to the setting of the price to "faux" lets in the use of fake timers for capabilities which includes "setTimeout"
 	timers: "real",
	// This property suggests the Jest to a map from regular expressions to paths to transformers
 	transform: null,
	// This configuration shows the Jest to an array of regex expression sample strings which are matched towards all source record paths, matched documents will pass transformation
 	transformIgnorePatterns: [
   	"/node_modules/"
 	],
	// It suggests that a map from ordinary regex to module names that permit to stub out assets with a single module
 	moduleNameMapper: {},
	// It suggests that an array of regex expression sample strings, matched against all module paths before considered 'visible' to the module loader
 	modulePathIgnorePatterns: [],
	// It suggests the Jest to prompt notifications for take a look at results
 	notify: false,
	// This configuration indicates the Jest which take a look at  test environment it need to use for the testing run
 	testEnvironment: "jest-environment-jsdom",
	// This configuration shows the Jest to the options so one can be passed to the testEnvironment
 	testEnvironmentOptions: {},
	// This configuration shows the Jest to add a location field to test the outcome of the run
 	testLocationInResults: false,
	// This configuration factors to the glob patterns Jest uses to detect test files
 	testMatch: [
   	"**/__tests__/**/*.js?(x)",
   	"**/?(*.)+(spec|test).js?(x)"
 	],
	// This configuration indicates the Jest to an array of regexp pattern strings that are matched towards all test paths, matched tests are skipped
 	testPathIgnorePatterns: [
   	"/node_modules/"
 	],
	// This configuration points to the regexp sample Jest makes use of to detect test files
 	testRegex: "",
	// This configuration shows the Jest to routinely restore mock state among every tests that are executed
 	restoreMocks: false,
	// This configuration suggests framework to the root listing that Jest should check for the test cases and modules inside them
 	rootDir: null,
	// This configuration shows the Jest framework to the list of paths to directories that Jest ought to use to look for files inside them
	roots: [
   	"<rootDir>"
 	],
 	// It indicates that an array of glob patterns indicating a hard and fast of files for which insurance statistics ought to be collected
 	collectCoverageFrom: null,
	// It indicates the directory in which Jest ought to output its coverage documents and test files
	coverageDirectory: 'coverage',
	// This property shows that an array of regexp sample strings used to skip the test coverage collection
 	coveragePathIgnorePatterns: [
   	"/node_modules/"
 	], 
	// It indicates that a list of reporter names that Jest makes use of whilst writing coverage reports
 	coverageReporters: [
   	"json",
   	"text",
   	"lcov",
   	"clover"
 	],
	// This property shows that an item that configures minimal threshold enforcement for coverage reports
 	coverageThreshold: null,
	// This property shows that framework have to make call of deprecated APIs and throw helpful errors messages
 	errorOnDeprecated: false,
	// This property indicates the Jest testing framework to force insurance collection from ignored files using a array of glob patterns
 	forceCoverageMatch: [],
	// It suggests the route to a module which exports an async characteristic this is triggered as soon as earlier than all test suites
 	globalSetup: null,
	// It shows the course of the module which exports an async function that is brought on as soon as after all test suites
 	globalTeardown: null,
	// It suggests the set of world variables that are required to be available in all test environments
 	globals: {},
	// It indicates an array of directory names to be searched recursively up from the requiring module's location
 	moduleDirectories: [
   	"node_modules"
 	],
	// This configuration shows the  Jest testing framework to an array of regexp sample strings which might be matched against all modules earlier than the module loader will mechanically return a mock data for the test case
 	unmockedModulePathPatterns: undefined,
	// This configuration shows the  Jest testing framework whether or not each separate test cases should be reported during the executed test run
 	verbose: true,
	// This configuration shows the  Jest testing framework to an array of regexp patterns which might be matched against all source document paths before re-running tests in watch mode
 	watchPathIgnorePatterns: [],
	// This configuration shows the Jest testing framework whether or not the watchman should be used for document crawling
 	watchman: true,
  };
```
 

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

```
//single_test.js:Jest testing tutorial for Selenium JavaScript Testing
/**
 * @jest-environment jest-environment-webdriver
 */
const webdriver = require('selenium-webdriver');
 
const script = require('jest');
 
const url = 'https://www.selenium.dev/'
 
const getElementXpath = async (driver, xpath, timeout = 3000) => {
  const el = await driver.wait(until.elementLocated(By.xpath(xpath)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};
 
 
const getElementName = async (driver, name, timeout = 3000) => {
  const el = await driver.wait(until.elementLocated(By.name(name)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};
 
const getElementId = async (driver, id, timeout = 3000) => {
  const el = await driver.wait(until.elementLocated(By.id(id)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};
 
// declaring the test group  This is our test case scenario that we will execute from our first test script. 
describe('executing test scenario on the website www.selenium.dev', () => {
    
    let driver;
 
    driver = new webdriver().build();
 
    // func to get the cloud driver eslint disable next line no undef
    await driver.get(
      ‘https://www.selenium.dev’,
    );
  }, 10000);
 
  afterAll(async () => {
    await driver.quit();
  }, 15000);
  
  test('it performs a validation of title on the home page', async () => {
    await browser.get(url)
    const title = await browser.findElement(by.tagName('h1')).getText()
    expect(title).toContain('SeleniumHQ Browser Automation')
  })
 
  test('it performs a validation of the search box on the page', async () => {
    const foundAndLoadedCheck = async () => {
      await until.elementLocated(by.id('search'))
      const value = await browser.findElement(by.id('search')).getText()
      return value !== '~'
    }
 
    await browser.wait(foundAndLoadedCheck, 3000)
    const search = await browser.findElement(by.id('search')).getText()
    expect(search).toEqual('')
  })
 
// declaring the test group
 
  describe('it captures a screenshot of the current page on the browser', () => {
    test('snap a picture by taking the screenshot', async () => {
      // files saved in ./reports/screenshots by default
      await browser.get(url)
      await browser.takeScreenshot()
    })
  })
})
```
 

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.

 
```
"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:

```
$  npm test
```
 

The output of the above test is :

![output3](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/output3.png)

**Code Coverage**

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

```
$  npm test --coverage
```


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

```
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.

```
jest_test
        | -- test_scripts
                    | -- module1-utils.js
              | -- module2-utils.js
                    | -- group_test.js
        | -- package.json
```
 
```
const checkPalindrome = (string) => string == string.split('').reverse().join('');
 
// function to check anagram //
const checkAnagram = (w1, w2) => {
 
    const regularize = (word) => {
        return word.toLowerCase().split('').sort().join('').trim();
    }
 
    return regularize(w1) === regularize(w2);
}
 
module.exports = {checkPalindrome, checkAnagram};
```
 
```
const sum = (vals) => {
        
    let sum = 0;
    
    vals.forEach((val) => {
        sum += val;
    });
    
    return sum;
}
 
const positive = (vals) => {
 
    return vals.filter((x) => { return x > 0; });
}
 
const negative = (vals) => {
 
    return vals.filter((x) => { return x < 0; });
}
 
module.exports = { sum, positive, negative };
```
 
```
const { checkPalindrome, checkAnagram } = require('./module1-utils');
 
const { sum, positive, negative } = require('./module2-utils');
 
 
describe('testing module1 utilities for any of the palindrome and anagram', () => {
 
    test.each( ["kayak" , " rotor" , "level" , " civic" , " redivider" , " madam" ])(
        'testing %s for any of the palindrome', (word) => {
            expect(checkPalindrome(word)).toBeTruthy();
        },
    );
 
    test.each( [["silent", "listen"], ["brag", "grab"], ["inch", "chin"]] )(
        'testing if %s and %s are any of the anagrams ', (w1, w2) => {
            expect(checkAnagram(w1, w2)).toBeTruthy();
        },
    );
});
 
describe('testing module2 utilities for sum, positive and negative values', () => {
    let vals;
    let sum_of_vals;
    let pos_vals;
    let neg_vals;
 
    beforeAll(() => {
        pos_vals = [2, 1, 3];
        neg_vals = [-2, -1, -1];
        vals = pos_vals.concat(neg_vals);
        sum_of_vals = vals.reduce((x, y) => x + y, 0);
    })
 
    test('it should fetch all the sum of vals and that should be 2', () => {
        expect(sum(vals)).toBe(sum_of_vals);
    });
 
    test('it should fetch all the positive values', () => {
        expect(positive(vals)).toEqual(pos_vals);
    });
 
    test('it should fetch all the negative values', () => {
        expect(negative(vals)).toEqual(neg_vals);
    });
});
```
 

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

```
$ npm test
or 
$ npm Jest groups_test.js
```
 

**Output** :

![output2](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/output2.png)

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](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/desired-capabilities-generator.png)

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

```
const capabilities = {
  'build': 'Jest-Selenium-Webdriver-Test', // Build Name to be display in the test logs
  'browserName': 'chrome', // Name of the browser to use in our test
  'version':'74.0', // browser version to be used to use in our test
  'platform': 'WIN10', //  Name of the Operating System that provides a platform for execution
  'video': true, // a flag which allows us to capture video.
  'network': true, // a flag which opts us whether to capture network logs
  'console': true, // a flag which allows us whether to capture console logs
  'visual': true // a flag which opts us whether to capture visual
};
```
 

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](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/access-key.png)

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

![automation-dashboard](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/automation-dashboard.png)

### 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:

 
```
jest_test
        | -- test_scripts
                    | -- single_test.js
        | -- jest.config.js 
  | -- package.json
```


```
/**
 * @jest-environment jest-environment-webdriver
 */
const webdriver = require('selenium-webdriver');
const {until} = require('selenium-webdriver');
const {By} = require('selenium-webdriver');
 
username= process.env.LT_USERNAME || "irohitgoyal", // Lambda Test User name
accessKey=  process.env.LT_ACCESS_KEY || "12345678987653456754" // Lambda Test Access key
 
const capabilities = {
  'build': 'Jest Automation Selenium Webdriver Test Script', // Build Name to be display in the test logs in the user interface
  'browserName': 'chrome', // Name of the browser to use in our test
  'version':'74.0', // browser version to be used
  'platform': 'WIN10', //  Name of the Operating System to be used
  'video': true, // flag that provides us an option to capture video.
  'network': true, // flag that provides us an option  whether to capture network logs
  'console': true, // flag that provides us an option whether to capture console logs
  'visual': true // flag that provides us an option whether to capture visual
};
 
 
const getElementXpath = async (driver, xpath, timeout = 3000) => {
  const el = await driver.wait(until.elementLocated(By.xpath(xpath)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};
 
const getElementId = async (driver, id, timeout = 3000) => {
  const el = await driver.wait(until.elementLocated(By.id(id)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};
 
const getElementName = async (driver, name, timeout = 3000) => {
  const el = await driver.wait(until.elementLocated(By.name(name)), timeout);
  return await driver.wait(until.elementIsVisible(el), timeout);
};
 
 
const url = 'https://www.lambdatest.com/'
 
// declaring the test group
describe('www.lambdatest.com/#index', () => {
    
    let driver;
// Build the web driver that we will be using in Lambda Test
  beforeAll(async () => {
    driver = new webdriver.Builder()
      .usingServer('https://'+ username +':'+ accessKey  +'@hub.lambdatest.com/wd/hub')
      .withCapabilities(capabilities)
      .build();
 
    // func to get the cloud driver eslint-disable-next-line no-undef
    await driver.get(
      `https://www.lambdatest.com`,
    );
  }, 10000);
 
  afterAll(async () => {
    await driver.quit();
  }, 15000);
  
  test('check for the rendering of the home page', async () => {
    await browser.get(url)
    const title = await browser.findElement(by.tagName('h1')).getText()
    expect(title).toContain('Perform Automated and Live Interactive Cross Browser Testing')
  })
 
  test('check whether the user email attribute is present', async () => {
    const foundAndLoadedCheck = async () => {
      await until.elementLocated(by.id('useremail'))
      const value = await browser.findElement(by.id('useremail')).getText()
      return value !== '~'
    }
 
    await browser.wait(foundAndLoadedCheck, 3000)
    const useremail = await browser.findElement(by.id('useremail')).getText()
    expect(useremail).toEqual('')
  })
 
// declaring the test group
 
  describe('take a screenshot of the web page from the browser', () => {
    test('save a picture by taking the screenshot', async () => {
      // files saved in ./reports/screenshots by default
      await browser.get(url)
      await browser.takeScreenshot()
    })
  })
})
```


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:

```
$ 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:**

![output](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/output.png)

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](https://www.lambdatest.com/blog/wp-content/uploads/2020/04/screenshot.png)

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.


## 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!**