This tutorial deep dives into performing JavaScript automation testing using frameworks like Playwright, Cypress Jest, Jasmine, and Mocha over the cloud.
OVERVIEW
According to the recent Stack Overflow Survey, JavaScript has been named the most commonly used programming language for over ten years. As a result, most developers of web applications use JavaScript to create all manner of apps.
As it becomes vital to build these applications, developers are urged to ship them at greater speed and higher quality. This is where JavaScript automation testing comes to the rescue.
In this tutorial, you will learn about JavaScript automation testing, front-end frameworks for testing, and how to run automated tests at scale on a cloud Selenium Grid.
JavaScript automation testing is the process of using JavaScript to write test scripts and run them using JavaScript testing frameworks without any human interference.
It is employed by developers and software testers to verify that a software or web application functions correctly during user interactions. This form of testing is applied across multiple stages of software testing, encompassing various levels of testing processes.
To automate the process of test execution, you can leverage JavaScript testing frameworks, libraries, test runners, and assertion libraries.
You need an IDE (e.g., Visual Studio Code), Node.js, and Node Package Manager (NPM) installed in your local machine to get started with JavaScript testing frameworks.
Here, we will discuss a few JavaScript testing frameworks for automation testing:
Selenium is an open-source automation testing suite widely used for testing web applications across different browsers and platforms. It provides tools and libraries that aid in automating web browser interactions, including Selenium WebDriver for browser automation, Selenium IDE for record-and-playback testing, and Selenium Grid for parallel test execution across multiple environments.
Selenium WebDriver provides various methods to interact with or locate different web elements on a web page using locator strategies, such as ID, ClassName, and XPath.
By distributing test execution across multiple nodes, Selenium Grid enables faster test execution, improves test coverage, and enhances the efficiency of the testing process. This makes it a valuable tool for organizations looking to scale their automated testing efforts and ensure comprehensive browser compatibility testing.
Data obtained from the Selenium GitHub repository proves its popularity as a JavaScript testing framework.
At the time of writing this tutorial on JavaScript automation testing, the Selenium WebDriver had 1,885,982 weekly downloads on npmjs.com. Selenium WebDriver downloads graph in the past year looks as shown below according to NPM trends.
The steps below show how to install and use Selenium WebDriver to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or your IDE of choice.
Step 2: Run the command below on the command line to initialize a new Node.js project.
npm init -y
Once the command is executed, it will create a package.json file to manage project dependencies.
Step 3: Install Selenium WebDriver and the WebDriver for the browser of your choice. In this case, use the Chrome WebDriver.
npm install selenium-webdriver chromedriver
Step 4: Create a new file called test.js in your project folder and add the code below that opens the Firefox browser, navigates to a URL, and fills input fields.
const { Builder, By, Key, until } = require("selenium-webdriver");
(async function example() {
let driver = await new Builder().forBrowser("firefox").build();
try {
await driver.get(
"https://www.lambdatest.com/selenium-playground/simple-form-demo"
);
const sum1 = await driver.findElement(By.id("sum1"));
await sum1.sendKeys(2, Key.RETURN);
const sum2 = await driver.findElement(By.id("sum2"));
await sum2.sendKeys(3, Key.RETURN);
const sum = await driver.findElement(
By.xpath("//button[normalize-space()='Get Sum']")
);
await sum.click();
} finally {
console.log("Test Run Successfully");
await driver.quit();
}
})();
Step 5: Run the command below on the command line to execute the test script.
node test.js
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
Playwright is an open-source automation testing library built by Microsoft for web testing. The library enables testers to run reliable end-to-end tests for modern web apps. It also allows testing on Chromium, Firefox, and WebKit-based browsers like Safari with a single API.
The Playwright library is cross-platform, enabling testers to run tests on Windows, Linux, and macOS, locally or on Continuous Integration(CI), headless or headed. Moreover, Playwright is cross-language, allowing the Playwright API in JavaScript, TypeScript, Python, .Net, and Java.
Also, Playwright enables testers to test mobile web using native mobile emulation of Google Chrome for Android and mobile Safari. The same rendering engine works on your Desktop and in the cloud.
When running tests, the Playwright waits for elements to be actionable before performing actions. Playwright combines the auto-wait feature with a rich set of introspection events to eliminate the need for timeouts, which are the primary cause of flaky tests.
Playwright, which has web-first assertions explicitly created for the dynamic web. Here, checks are automatically retried until the necessary conditions are met. Also, Playwright enables you to configure test retry strategy, capture execution traces, videos, and screenshots to eliminate flakes.
The Playwright testing framework is aligned with the modern browsers architecture and runs tests out-of-process, which makes it free of the typical in-process test runner limitations.
The framework can handle test scenarios that span multiple tabs, origins, and users. Also, Playwright allows you to create scenarios with different contexts for different users and run them against your server, all in one test.
Playwright enables testers to create a browser context for each test where the context is equivalent to a brand new browser profile, delivering full test isolation with zero overhead.
The Playwright testing framework also offers powerful tools like Codegen, Playwright Inspector, and Trace Viewer. Codegen generates tests by recording your actions and saving them in any language.
The Playwright Inspector inspects the page, generates selectors, steps through the test execution, sees click points, and explores execution logs. Trace Viewer captures all the information to investigate the test failure. The Trace Viewer tool contains test execution screencasts, live DOM snapshots, action explorer, test source, and many more.
According to data obtained from the Playwright GitHub repository, Playwright is a prevalent JavaScript testing framework, with:
At the time of writing this tutorial on JavaScript automation testing, the Playwright testing framework had 4,063,375 weekly downloads, according to npmjs.com. Below is a graph showing Playwright's downloads in the past year on NPM trends.
The steps below show how to install and use Playwright to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or text editor of your choice.
Step 2: Run the command below on the command line to install Playwright in your project and select the following to get started:
npm init playwright@latest
Step 3: Create a file called test.spec.js in the Tests folder in your project folder. Add the code below to the test.spec.js file.
const { test, expect } = require("@playwright/test");
test("Google homepage title", async ({ page }) => {
await page.goto("https://www.google.com/");
const title = await page.title();
expect(title).toBe("Google");
});
The code above opens the Chrome browser, creates a new page, and navigates to the Google homepage. It will then get the page's title and assert that it equals "Google".
Step 4: To run the test, run the command below on the command line.
npx playwright test
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
Cypress is a JavaScript-based end-to-end testing framework commonly used for testing web applications. It allows you to write and execute tests in a real browser, providing a way to simulate user interactions and assert expected behaviors.
It enables you to write all types of tests, including end-to-end tests, component tests, and integration tests.
As you change your test code, Cypress automatically reloads the application and test runner, providing a real-time feedback loop. As a tester, this feature greatly improves your testing workflow.
Cypress can intercept and modify network requests and responses. This allows you to stub or mock API calls, simulate different network conditions, and test edge cases that involve asynchronous behavior.
Also, Cypress can capture screenshots and record videos of your test runs, which can help debug or share test results with your team.
Data obtained from the Cypress GitHub repository proves its popularity as a JavaScript test framework.
At the time of writing this tutorial on JavaScript automation testing, the Cypress testing framework had 5,400,230 downloads on npmjs.com. Cypress automation testing framework downloads graph in the past year looks as shown below according to NPM trends.
The steps below show how to install and use Cypress to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or text editor of your choice.
Step 2: Run the command below on the command line to install Cypress in your project, version 12.17.2, when writing this tutorial on JavaScript automation testing. Adding --save-dev to the command helps save the name and version of Cypress in the dev-dependency object.
npm install --save-dev cypress
Step 3: Run the following command on the command line to launch the Cypress Test Runner.
npx cypress open
Step 4: On the Cypress Test Runner, select E2E Testing and continue.
Step 5: Choose Chrome as your preferred browser for E2E testing and click the Start E2E Testing in Chrome button.
Step 6: Select Create new spec on the Chrome browser that launches.
Step 7: Name the spec as test and click the Create spec button.
Step 8: In your project folder, add the following code to the test.cy.js spec file created.
/// <reference types="cypress" />
describe("example to-do app", () => {
beforeEach(() => {
cy.visit("https://example.cypress.io/todo");
});
it("displays two todo items by default", () => {
cy.get(".todo-list li").should("have.length", 2);
cy.get(".todo-list li").first().should("have.text", "Pay electric bill");
cy.get(".todo-list li").last().should("have.text", "Walk the dog");
});
it("can add new todo items", () => {
const newItem = "Feed the cat";
cy.get("[data-test=new-todo]").type('${newItem}{enter}');
cy.get(".todo-list li")
.should("have.length", 3)
.last()
.should("have.text", newItem);
});
it("can check off an item as completed", () => {
cy.contains("Pay electric bill")
.parent()
.find("input[type=checkbox]")
.check();
cy.contains("Pay electric bill")
.parents("li")
.should("have.class", "completed");
});
});
Step 9: On the Chrome browser that launched, click the test.cy.js spec file to run the test.
Once the test finishes running, you should see the results on the Chrome browser as shown below.
Puppeteer is a Node.js library developed by the Chrome team at Google that provides a high-level API to control Chrome/Chromium over the DevTools Protocol. Puppeteer runs in headless mode by default but can be configured to run in full ("headful") Chrome/Chromium.
You can capture screenshots and generate PDF files of your web application, which can help you in visual testing and generating reports. In addition, you can capture a timeline trace of your web application to help diagnose performance issues.
Data obtained from the Puppeteer GitHub repository proves its popularity as a JavaScript test framework.
At the time of writing this tutorial on JavaScript automation testing, the Puppeteer testing framework had 4,891,404 weekly downloads on npmjs.com. The Puppeteer downloads graph in the past year looks as shown below according to NPM trends.
The steps below show how to install and use Puppeteer to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or your IDE of choice.
Step 2: Run the command below on the command line to install Puppeteer in your project.
npm install puppeteer
Step 3: Create a file called test.js in your project folder and add the following code.
const puppeteer = require("puppeteer");
(async () => {
// Launch the browser and open a new blank page
const browser = await puppeteer.launch({ headless: "new" });
const page = await browser.newPage();
// Navigate the page to a URL
await page.goto("https://www.google.com");
const pageTitle = await page.title();
console.log(pageTitle);
await browser.close();
})();
Step 4: Run the command below on the command line to execute the test.
node test.js
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
Mocha is a widely used JavaScript testing framework running on Node.js. Mocha tests run in a sequential or serial order, which allows for flexible and accurate reporting while mapping uncaught exceptions to the correct test cases.
This allows you to define test suites and individual test cases using a clear and readable syntax. Mocha has built-in support for testing asynchronous code, such as callbacks, promises, and async/await functions. The automated test framework provides mechanisms to handle async operations and ensure proper test completion.
The Mocha testing framework offers hooks that allow you to define pre-test and post-test actions. Six hooks used in testing by Mocha to set up or load up preconditions used in the testing are it(), describe(), beforeEach(), afterEach(), before(), and after().
Mocha integrates well with code coverage tools like Istanbul. By combining Mocha with a coverage tool, you can measure the effectiveness of your tests and identify areas of your code that are not adequately covered by tests.
Data obtained from the Mocha GitHub repository proves its popularity as a JavaScript test framework.
At the time of writing this tutorial on JavaScript automation testing, the Mocha testing framework had 7,459,634 downloads on npmjs.com. Mocha automation testing framework downloads graph in the past year looks as shown below according to NPM trends.
The steps below show how to install and use Mocha to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or text editor of your choice.
Step 2: Run the command below on the command line to install Mocha in your project, along with an assertion library Chai. It provides a set of expressive and readable assertion styles.
npm install --save-dev mocha chai
Step 3: Run the command below on the command line to install Selenium WebDriver.
npm install selenium-webdriver
Step 4: Run the command below on the command line to install Chrome WebDriver.
npm install chromedriver
Step 5: Create a file called test.js and add the code below.
var webdriver = require("selenium-webdriver");
function simpleForm() {
var driver = new webdriver.Builder().forBrowser("chrome").build();
driver.get("https://www.lambdatest.com/selenium-playground/simple-form-demo").then(function () {
driver.findElement(webdriver.By.id("sum1")).sendKeys(2);
driver.findElement(webdriver.By.id("sum2")).sendKeys(3);
driver.findElement(webdriver.By.xpath("//button[normalize-space()='Get Sum']")).click().then(function () {
setTimeout(function () {
console.log("Test Run Successfully");
driver.quit();
}, 5000);
});
});
}
simpleForm();
Step 6: To run the test, run the command below on the command line.
node test.js
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
Jasmine is an open-source testing framework for writing and running tests in JavaScript. It is a Behavior-Driven Development (BDD) framework that focuses on performing test cases similar to user behavior on a web application.
This JavaScript testing framework is suitable for unit testing, where it is heavily influenced by other unit testing frameworks such as ScrewUnit, JSSpec, JSpec, and RSpec.
According to data obtained from the Jasmine GitHub repository, it is a prevalent JavaScript testing framework.
At the time of writing this tutorial on JavaScript automation testing, Jasmine testing framework had 1,534,668 weekly downloads, according to npmjs.com. Below is a graph showing Jasmine's downloads in the past year on NPM trends.
The steps below show how to install and use Jasmine to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or text editor of your choice.
Step 2: Run the command below on the command line to install Jasmine in your project. Adding --save-dev to the command helps save the name and version of Jasmine in the dev-dependency object.
npm install --save-dev jasmine
Step 3: To initialize Jasmine in your project, run the command below on the command line.
npx jasmine init
Step 4: Configure the npm test script to run the Jasmine JavaScript tests when the command npm test is executed. To do that, update the package.json file and add a scripts section, as shown below.
"scripts": {
"test": "jasmine"
}
The package.json file code should now look as shown below.
{
"scripts": {
"test": "jasmine"
},
"devDependencies": {
"jasmine": "^5.1.0"
}
}
Step 5: Run the command below on the command line to install Selenium WebDriver.
npm install selenium-webdriver
Step 6: Create a file called form.spec.js in the Spec folder and add the following code.
const { Builder, By, Key, until } = require("selenium-webdriver");
let driver;
beforeAll(async () => {
driver = await new Builder().forBrowser("chrome").build();
});
afterAll(async () => {
await driver.quit();
});
describe("Simple Form Demo", () => {
it("should fill form input fields", async () => {
await driver.get(
"https://www.lambdatest.com/selenium-playground/simple-form-demo"
);
const sum1 = await driver.wait(until.elementLocated(By.id("sum1")), 5000);
await sum1.sendKeys(2);
});
});
Step 7: To run the test, run the command below on the command line.
npx jasmine spec/form.spec.js
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
Jest is a testing framework developed by Meta (earlier Facebook) that is widely used for unit testing and end-to-end testing.
It works with projects using Babel, TypeScript, Node.js, React, Angular, Vue.js, and Svelte, requiring zero configuration or setup from the user, giving a seamless testing experience out of the box.
The JavaScript testing framework supports snapshot testing, which allows you to capture the expected output of a component and compare it against the base image when running tests. Snapshot testing makes it easy to detect unintended changes in the test output, ensuring your code behaves as expected.
Jest includes built-in code coverage reporting, which provides you with insights into how much of your code is covered by tests.
The Jest testing framework offers mocking and spying capabilities to isolate dependencies and control the behavior of functions, modules, and objects during testing. Using mocking and spying, Jest allows you to create mock versions of modules, simulate specific behaviors and verify function calls and interactions with dependencies.
Data obtained from the Jest GitHub repository proves its popularity as a JavaScript test framework.
At the time of writing this tutorial on JavaScript automation testing, the Jest testing framework had 18,869,642 downloads on npmjs.com. Jest automation testing framework downloads graph in the past year looks as shown below according to NPM trends.
The steps below show you how to install and use Jest to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or text editor of your choice.
Step 2: Run the command below on the command line to install Jest in your project. Adding --save-dev to the command helps save the name and version of Jest in the dev-dependency object.
npm install --save-dev jest
Step 3: Run the command below on the command line to install Selenium WebDriver.
npm install selenium-webdriver
Step 4: Create a file called form.test.js in your project folder and add the following code.
const { Builder, By, Key, until } = require("selenium-webdriver");
let driver;
beforeAll(async () => {
driver = await new Builder().forBrowser("chrome").build();
});
afterAll(async () => {
await driver.quit();
});
describe("Simple Form Demo", () => {
test("should fill form input fields", async () => {
await driver.get(
"https://www.lambdatest.com/selenium-playground/simple-form-demo"
);
const sum1 = await driver.wait(until.elementLocated(By.id("sum1")), 5000);
await sum1.sendKeys(2);
});
});
Step 5: To run the test, run the command below on the command line.
npx jest form.test.js
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
WebdriverIO is a test automation framework for Node.js used for running end-to-end, unit, and component tests in the browser. The test automation framework allows you to run tests based on WebDriver, WebDriver BiDi, and Appium automation technology.
It supports BDD or TDD test frameworks, running locally or in the cloud. The framework allows you to run tests in actual browsers or mobile devices used by your users.
Also, when running tests, WebdriverIO automatically waits for elements to appear before interacting with them.
The WebdriverIO test runner comes with a command line interface that provides a powerful configuration utility that helps you create your test setup in less than a minute. It lets you pick from available test framework integrations and easily allows you to add all supported reporter and service plugins!
According to data obtained from the WebdriverIO GitHub repository, WebdriverIO is a prevalent JavaScript testing framework.
At the time of writing this tutorial on JavaScript automation testing, the WebdriverIO testing framework had 1,093,933 weekly downloads, according to npmjs.com. Below is a graph showing WebdriverIO's downloads in the past year on NPM trends.
The steps below show how to install and use WebdriverIO to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or text editor of your choice.
Step 2: Run the command below on the command line to install WebdriverIO in your project.
npm install @wdio/cli
Step 3: Run the command below on the command line to create a configuration file for WebdriverIO. This command will run you through a series of questions to get WebdriverIO set up. The latest version of WebdriverIO at the time of writing this tutorial is 8.31.0.
npx wdio config
Step 4: In your project folder, create a folder called Tests. In the Tests folder, create a folder called Specs. Then create a file called test.e2e.js inside the Specs folder and add the following code.
const { expect, browser, $ } = require("@wdio/globals");
describe("Form Submit Demo", () => {
it("should fill form input fields", async () => {
await browser.url(
'https://www.lambdatest.com/selenium-playground/ajax-form-submit-demo'
);
await $("#title").setValue("John Doe");
await $("#description").setValue("Hello there");
await $("#btn-submit").click();
});
});
Step 5: Run the command below on the command line to run the test.
npm run wdio
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
Nightwatch.js is a testing framework written in Node.js for performing automated end-to-end testing on web applications and websites across all major browsers. It uses the W3C WebDriver API to interact with various browsers.
The automation testing framework aims to simplify the process of writing and running various types of tests, including end-to-end tests, unit tests, and integration tests. Nightwatch performs browser automation using the industry standard protocol WebDriver, defined as a W3C standard specification.
Nightwatch can also be used for distributed cross-browser end-to-end testing at scale with the Selenium Server (also known as Selenium Grid), an open-source project written in Java that manages a network of WebDriver nodes.
According to NightwatchJS GitHub repository data, NightwatchJS is a prevalent JavaScript testing framework.
At the time of writing this tutorial on JavaScript automation testing, the NightwatchJS testing framework had 121,378 weekly downloads, according to npmjs.com. Below is a graph showing NightwatchJS's downloads in the past year on NPM trends.
The steps below show how to install and use NightwatchJS to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or text editor of your choice.
Step 2: Run the command below on the command line to initialize NightwatchJS in your project. Then, answer the simple set of questions that follow to complete the Nightwatch installation.
npm init nightwatch
Step 3: Create a folder called Tests in the project folder. Then, create a file called test.js inside the Tests folder and add the following code.
describe("Simple Form Demo", function () {
const sum1 = element("#sum1");
const sum2 = element("#sum2");
const sum = element('form button[type="button"]');
const result = element("#addmessage");
it("should fill form input fields", async function () {
await browser.navigateTo(
"https://www.lambdatest.com/selenium-playground/simple-form-demo"
);
await browser.sendKeys(sum1, 2);
await browser.sendKeys(sum2, 3);
await browser.click(sum);
await expect(result).text.toContain("5");
});
});
Step 4: Run the command below on the command line to run the tests.
npx nightwatch . ests est.js
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
Karma is a popular JavaScript test runner that allows you as a developer to execute tests in real browsers and real devices such as phones, tablets, or on a headless PhantomJS instance.
The JavaScript test runner supports many testing frameworks like Jasmine, Mocha, and QUnit.
Data obtained from the Karma GitHub repository proves its popularity as a JavaScript test runner.
At the time of writing this tutorial on JavaScript automation testing, Karma had 2,064,480 weekly downloads on npmjs.com. The Karma downloads graph in the past year looks as shown below according to NPM trends.
The steps below show how to install and use Karma to run automated tests in JavaScript.
Step 1: Create a project folder and open it on Visual Studio Code or your IDE of choice.
Step 2: Run the command below on the command line to install the Karma JavaScript test runner in your project.
npm install --save-dev karma
Step 3: Run the command below on the command line to install Jasmine since we decided to use it as a test framework.
npm install jasmine
Step 4: Run the command below on the command line to install Karma Chrome Launcher and Selenium WebDriver.
npm install karma-chrome-launcher selenium-webdriver
Step 5: Create a file called karma.conf.js and add the following code.
module.exports = function (config) {
config.set({
frameworks: ["jasmine"],
files: ["test/**/*.spec.js"], // Your test files
browsers: ["Chrome"], // You can use other browsers as needed
reporters: ["progress"],
singleRun: true,
autoWatch: false,
});
};
Step 6: Create a folder called Src in your project folder. In the Src folder, create a file called karma.test.js and add the following code.
const { Builder, By, Key, until } = require("selenium-webdriver");
let driver;
beforeAll(async () => {
driver = await new Builder().forBrowser("chrome").build();
});
afterAll(async () => {
await driver.quit();
});
describe("Simple Form Demo", () => {
it("should fill form input fields", async () => {
await driver.get(
"https://www.lambdatest.com/selenium-playground/simple-form-demo"
);
const sum1 = await driver.wait(until.elementLocated(By.id("sum1")), 5000);
await sum1.sendKeys(2);
});
});
Step 7: Run the command below on the command line to run the test.
npx karma start karma.conf.js
Once the command is done running, you should be able to see the results of the tests on the command line, as shown below.
Note : Run your JavaScript tests over 3000+ browser and operating system configurations. Try LambdaTest Now!
While JavaScript automation testing has immense benefits, it comes with challenges, such as flaky, ineffective, and unmanageable tests. In this section of this tutorial on JavaScript automation testing, you will learn some of the best practices to follow when writing automated JavaScript tests.
As a tester, before writing and running tests, you need to choose the JavaScript automation testing tool or framework that enables you to reduce costs, accelerate developer feedback time, reduce flakiness, enhance efficiency, and accelerate the delivery of high-quality applications.
Here are some key factors to consider when choosing the JavaScript automation testing tool:
While performing JavaScrip automation testing, you should divide test code into modular components to make it readable and maintainable. You can use design patterns to separate the test code from the application’s structure.
In your test code, you can use design patterns such as:
A good design pattern helps minimize code duplication and updates as you introduce changes in your application.
When writing tests, you must write clear and descriptive test names. The test names should show the purpose of the test and its intent.
A test name should consist of what is being tested, the different scenarios under which you are testing, and the expected result of the test.
As a tester, you should group related tests using a suite or describe blocks when writing tests.
Mocking in JavaScript for automation testing is a technique used to isolate the component being tested from its dependencies and to simulate the behavior of real objects. It involves creating mock objects for real objects within the system.
It is particularly useful for unit testing, where it can help control side effects, introduce chaos, and ensure that tests are more resilient to changes in the codebase. By using mocking, testers can verify that the isolated parts of the system are performing as expected and identify and fix problems before the software is released to end-users.
Parameterizing tests in automation testing is running the same test with different input values or parameters. This approach helps to avoid repetitiveness in test case construction and reduces the time and effort required to execute multiple tests with varying data.
In this section of this tutorial on JavaScript automation testing, we will learn how to run tests using different JavaScript automation testing frameworks.
In this case, we will use three browser and operating system combinations to test whether a user can visit an e-commerce website, search for an item, add the item to the cart, and then check out the item.
The browser and operating system combinations can be:
Here, we will be using different JavaScript testing frameworks to run tests on a scalable cloud grid like LambdaTest. It is an AI-powered test orchestration and execution cloud-based platform facilitating automation testing with JavaScript across large farms of over 3000+ browser and OS combinations.
Subscribe to the LambdaTest YouTube channel for more videos on Selenium testing, Playwright testing, Cypress testing, and more.
To define your desired browser and operating system combinations, you can use LambdaTest Capabilities Generator.
Follow the steps below to generate browser and operating system combinations.
Step 1: On the Capabilities Generator Page, select the programming language you are using to run your tests. In this case, we use JavaScript and can select Node JS, a JavaScript framework.
Step 2: Select Selenium as the tool you will be using to run the end-to-end tests.
Step 3: Then select Selenium 4 on the right.
Step 4: Configure your capabilities by selecting a browser and browser version.
Step 5: Click Configure Advanced Capabilities and select the operating system.
Step 6: Scroll down to the Build Settings section and fill out the input fields as shown below.
Step 7: Scroll down to the Test Configuration section and fill out the input field as shown below.
On the right, you can now see the capabilities presented in a code format that you can copy and use in your test script.
For our test cases, below are capabilities for browser and operating system combinations we want to test on an eCommerce website add-to-cart and checkout functionality.
Chrome 118.0 + Windows 10
Safari 17.0 + macOS Sonoma
Firefox 118.0 + Linux
In this case, we will run a test case scenario to test whether a user can visit an e-commerce website and add an item to the cart. Below is the test case scenario.
Test Scenario:
|
In this section of this tutorial on JavaScript automation testing, we will learn how to create and run a test script using the Playwright framework.
Step 1: Run the command below on the command line to install Playwright in your project.
npm i playwright
Step 2: Run the command below on the command line to install Playwright dependencies.
npm i -D @playwright/test
Step 3: Configure the npm testscript to run the Playwright tests when the command npm test is executed. To do that, update the package.json file and add a scripts section, as shown below.
"scripts": {
"test": "npx playwright test"
},
The package.json file code should now look as shown below.
{
"scripts": {
"test": "npx playwright test"
},
"dependencies": {
"playwright": "^1.40.0"
},
"devDependencies": {
"@playwright/test": "^1.40.0"
}
}
Step 4: In the Playwright folder, create a file called playwright.config.js and add the following code.
const { devices } = require('@playwright/test')
// Playwright config to run tests on LambdaTest platform and local
const config = {
testDir: 'tests',
testMatch: '**/*.spec.js',
timeout: 60000,
use: {
viewport: null,
baseURL: 'https://ecommerce-playground.lambdatest.io'
},
projects: [
{
name: 'chrome:latest:MacOS Catalina@lambdatest',
use: {
viewport: { width: 1920, height: 1080 }
}
},
{
name: 'chrome:latest:Windows 10@lambdatest',
use: {
viewport: { width: 1920, height: 1080 }
}
},
{
name: 'MicrosoftEdge:90:Windows 10@lambdatest',
use: {
viewport: { width: 1920, height: 1080 }
}
},
{
name: 'pw-firefox:latest:Windows 10@lambdatest',
use: {
viewport: { width: 1920, height: 1080 }
}
},
{
name: 'pw-webkit:latest:MacOS Big sur@lambdatest',
use: {
viewport: { width: 1920, height: 1080 }
}
}
]
}
module.exports = config
In the code above, the configuration file sets up test parameters, defines a base URL, and specifies configurations for different test projects, each targeting a specific browser and platform combination for running tests on the LambdaTest platform.
Step 5: Create a file called lambdatest-setup.js in the Playwright folder, and add the following code.
const base = require('@playwright/test')
const path = require('path')
const { chromium } = require('playwright')
// LambdaTest capabilities
const capabilities = {
'browserName': 'Chrome', // Browsers allowed: 'Chrome', 'MicrosoftEdge', 'pw-chromium', 'pw-firefox' and 'pw-webkit'
'browserVersion': 'latest',
'LT:Options': {
'platform': 'Windows 10',
'build': 'Playwright Build - Full suite',
'name': 'Playwright Test',
'user': "Username",
'accessKey': "accessKey",
'network': true,
'video': true,
'console': true,
}
}
// Patching the capabilities dynamically according to the project name.
const modifyCapabilities = (configName, testName) => {
let config = configName.split('@lambdatest')[0]
let [browserName, browserVersion, platform] = config.split(':')
capabilities.browserName = browserName ? browserName : capabilities.browserName
capabilities.browserVersion = browserVersion ? browserVersion : capabilities.browserVersion
capabilities['LT:Options']['platform'] = platform ? platform : capabilities['LT:Options']['platform']
capabilities['LT:Options']['name'] = testName
}
const getErrorMessage = (obj, keys) => keys.reduce((obj, key) => (typeof obj == 'object' ? obj[key] : undefined), obj)
exports.test = base.test.extend({
page: async ({ page, playwright }, use, testInfo) => {
// Configure LambdaTest platform for cross-browser testing
let fileName = testInfo.file.split(path.sep).pop()
if (testInfo.project.name.match(/lambdatest/)) {
modifyCapabilities(testInfo.project.name, '${testInfo.title} - ${fileName}')
const browser = await chromium.connect({
wsEndpoint: 'wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}'
})
const ltPage = await browser.newPage(testInfo.project.use)
await use(ltPage)
const testStatus = {
action: 'setTestStatus',
arguments: {
status: testInfo.status,
remark: getErrorMessage(testInfo, ['error', 'message'])
}
}
await ltPage.evaluate(() => {},
'lambdatest_action: ${JSON.stringify(testStatus)}')
await ltPage.close()
await browser.close()
} else {
// Run tests in local in case of local config provided
await use(page)
}
}
})
The code above sets up Playwright tests to run on LambdaTest by dynamically configuring capabilities based on the project name and connecting to LambdaTest for cross browser testing. It also includes functionality to handle error reporting on LambdaTest. If the project name does not match LambdaTest, it runs the tests locally.
Step 6: Create a folder called Tests in the PLAYWRIGHT folder. Then, create a file called addToCart.spec.js in the Tests folder and add the following code.
const { test } = require('../lambdatest-setup')
const { expect } = require('@playwright/test')
test.describe('Ecommerce Site Tests', () => {
test('Add to cart', async ({ page }) => {
// Navigate to base url
await page.goto('https://ecommerce-playground.lambdatest.io')
// Click Shop by Category
await page.locator('text=Shop by Category').click();
// Click Phone, Tablets & Ipod
await page.locator('text=Phone, Tablets & Ipod').click();
// Hover over product
await page.locator('text=Add to Cart Add to Wish List iPhone $123.20 iPhone is a revolutionary new mobile phone').hover()
// Wait for element
await expect(page.locator('text=Add to Cart Add to Wish List iPhone $123.20 iPhone is a revolutionary new mobile phone >> button >> nth=0')).toBeVisible()
await page.waitForTimeout(2000)
// Click add to cart
await page.locator('text=Add to Cart Add to Wish List iPhone $123.20 iPhone is a revolutionary new mobile phone >> button').first().click()
// Click view cart
await page.locator('text=View Cart').click()
// Assert correct product added to cart
await expect(page.locator('#content >> text=iPhone')).toBeVisible()
})
});
Code Walkthrough:
A test object from lambdatest-setup.js file and expect function from @playwright/test, used for asserting in the test, are imported.
A test suite named Ecommerce Site Tests is described.
A test case within the Ecommerce Site Tests suite named Add to cart is described. The test case provides an asynchronous function that receives the page object, representing the browser page, as a parameter.
Inside the test block, the path for web elements on the e-commerce website we want to be tested is defined.
Step 8: Run the command below on the command line to run the tests.
npm run test
Once the command completes running, you should see on the command line that the tests have passed, as shown below.
In this section of this tutorial on JavaScript automation testing, we will learn how to create and run a test script using the Cypress framework.
Step 1: Run the command below on the command line to install Cypress in your project. Adding --save-dev to the command helps save the name and version of Jasmine in the dev-dependency object.
npm install --save-dev cypress
Step 2: Run the following command on the command line to launch the Cypress Test Runner.
npx cypress open
Step 3: On the Cypress Test Runner, select E2E Testing and click Continue.
Step 4: Choose Chrome as your preferred browser for E2E testing and click the Start E2E Testing in Chrome button.
Step 5: On the Chrome browser that launches, select Create new spec.
Step 6: Name the spec as test and click the Create spec button.
Step 7: Install the LambdaTest-Cypress CLI using the below command.
npm install -g lambdatest-cypress-cli
Step 8: Run the command below on the command line to generate lambdatest-config.json file that contains configurations like auth, capabilities, test settings, etc. which are needed to execute tests on LambdaTest successfully.
lambdatest-cypress init --cv=10
Step 9: Add the following code to the test.cy.js spec file created.
/// <reference types="cypress" />
describe("Ecommerce Site Tests", () => {
beforeEach(() => {
cy.visit("https://ecommerce-playground.lambdatest.io/");
});
it("Add To Cart", () => {
cy.contains('Components').click({ force: true })
cy.contains('iPhone').click({ force: true })
cy.contains('Buy').click({ force: true })
cy.contains('iPhone')
});
});
Code Walkthrough:
A describe block called Ecommerce Site Tests is declared.
A beforeEach hook that navigates to the e-commerce site website is created. The hook ensures that the test environment is set up before each test.
An it block for a test case called Add To Cart is created.
In the code above, the Cypress contains() command is used to find elements containing the texts Components, iPhone, and Buy and to assert that there should be an element containing the text iPhone to ensure an iPhone has been added to the cart successfully.
Step 10: In the lambdatest-config.json file, add the path of the tests files as shown below.
"run_settings": {
"reporter_config_file": "base_reporter_config.json",
"build_name": "Add To Cart",
"parallels": 1,
"specs": "./cypress/e2e/*.cy.js",
"ignore_files": "",
"network": false,
"headless": false,
"npm_dependencies": {
"cypress": "10"
}
},
Step 11: Run the command below on the command line to run the tests.
lambdatest-cypress run
Once the command runs, click the link on the command line and visit the LambdaTest Automation Dashboard to view your test results, as shown below.
In this section of this tutorial on JavaScript automation testing, we will learn how to create and run a test script using the Jasmine framework.
Step 1: Create a folder called JASMINE. Then, open the folder using a text editor of your choice. In this case, I am using Cursor.
Step 2: In the project folder, create a folder called Spec. In the Spec folder, create two folders called Tests and pageModel, as shown below.
Step 3: Run the command below on the command line to install Jasmine in your project.
npm install --save-dev jasmine
Adding –save-dev to the command helps save the name and version of Jasmine in the dev-dependency object.
Step 4: Run the command below on the command line to initialize Jasmine in your project.
npx jasmine init
Step 5: Configure the npm test script to run the Jasmine JS tests when the command npm test is executed. To do that, update the package.json file and add a scripts section, as shown below.
"scripts": {
"test": "jasmine"
},
The package.json file code should now look as shown below.
{
"scripts": {
"test": "jasmine"
},
"devDependencies": {
"jasmine": "^5.1.0"
}
}
Step 6: Install the latest version of the Selenium WebDriver in the project folder by running the command below on the command line.
npm install selenium-webdriver
Step 7: In the PageModel folder, create two files named main.js and addToCart.main.js, as shown below.
The naming convention main.js of the files means that the main.js file is the parent file while the other files are child files. It simply means the child files will inherit some methods from the parent file.
Step 8: Install the dotenv package for managing environment variables using the command below.
npm install dotenv
Step 9: Create a file called .env in the main directory and add your LambdaTest username and access key, shown below.
LT_USERNAME="Your Username"
LT_ACCESS_KEY="Your Access Key”
Step 10: In the main.js file, add the following code.
selenium = require("selenium-webdriver");
const { Builder, By, Key, until } = require("selenium-webdriver");
const { Select } = require("selenium-webdriver");
require("dotenv").config();
const username = process.env.LT_USERNAME;
const accessKey = process.env.LT_ACCESS_KEY;
var remoteHub = "https://" + username + ":" + accessKey + "@hub.lambdatest.com/wd/hub";
const chromeWindowsCapability = {
"browserName": "Chrome",
"browserVersion": "118.0",
"LT:Options": {
"username": username,
"accessKey": accessKey,
"platformName": "Windows 10",
"project": "JasmineSeleniumE2E",
"name": "E2E",
"w3c": true,
"plugin": "node_js-node_js"
}
}
const safariMacOSCapability = {
"browserName": "Safari",
"browserVersion": "17.0",
"LT:Options": {
"username": username,
"accessKey": accessKey,
"platformName": "macOS Sonoma",
"project": "JasmineSeleniumE2E",
"name": "E2E",
"w3c": true,
"plugin": "node_js-node_js"
}
}
const fireFoxLinuxcapability = {
"browserName": "Firefox",
"browserVersion": "118.0",
"LT:Options": {
"username": username,
"accessKey": accessKey,
"platformName": "Linux",
"project": "JasmineSeleniumE2E",
"name": "E2E",
"w3c": true,
"plugin": "node_js-node_js"
}
}
const getElementById = async (driver, id, timeout = 8000) => {
const el = await driver.wait(until.elementLocated(By.id(id)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
const getElementByXpath = async (driver, xpath, timeout = 8000) => {
const el = await driver.wait(until.elementLocated(By.xpath(xpath)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
const seleniumDriver = new selenium.Builder()
.usingServer(remoteHub)
.withCapabilities(chromeWindowsCapability)
.build();
class Main {
constructor() {
this.driver = seleniumDriver;
this.byId = getElementById;
this.byXpath = getElementByXpath;
}
}
module.exports = Main;
Code Walkthrough:
Since we are using Selenium to run the tests, Selenium WebDriver, until, select, and By are imported using the require function as shown below:
Variables username, accessKey, and remoteHub to be used in the test case are set.
Test capabilities are configured by passing browser, browser version, and operating system information with LambdaTest Selenium Grid capabilities through the capabilities object.
An async function called getElementById, which takes driver, id, and timeout parameters, is declared.
The driver parameter is an instance of a Selenium WebDriver used to control a browser. The id parameter is the ID of the HTML element you want to interact with. The timeout parameter is the maximum time in milliseconds that the getElementById function will wait for the element to become visible.
Inside the async function, a variable called el is declared. The variable value instructs the Selenium Driver to wait until the element with the targeted id is on the test URL. The elementLocated() method is used here.
Below is how the ID locator locates an element.
An object returned by the getElementById async function instructs the Selenium WebDriver to wait until the element targeted by the id is visible on the DOM. Visibility means that the element is not only displayed but also has a height and width that is greater than zero. The elementIsVisible() method is used here.
An async function called getElementByXpath with parameters driver, XPath, and timeout set to 8000 milliseconds is declared.
Inside the async function, a variable called el is declared, where the variable value instructs the Selenium WebDriver to wait until the element with the targeted XPath is located on the registration page of the e-commerce website, the elementLocated() method is used here.
Below is how an element is located by XPath.
An object returned by the getElementByXpath async function instructs the Selenium WebDriver to wait until the element we are targeting by XPath is present on the DOM of the registration page and visible. The elementIsVisible() method is used here.
A new instance of a Selenium WebDriver is initialized using the Builder design pattern.
The const declares a constant variable named seleniumDriver, which will hold the created Selenium WebDriver instance. The new selenium.Builder() creates a new instance of the Builder class provided by the Selenium library.
A JavaScript class called Main is created where the class has a constructor method, a special method called when an object of the class is created. The constructor method initializes the properties of the class.
A value of is assigned to this.driver property, a value of getElementById to this.byId property, and a value of getELementByXpath to this.byXpath property in this constructor method.
Finally, the Main class is exported to be used in other files.
Step 11: In the addToCart.main.js file, add the following code.
File: AddToCart.Main.js
const Main = require('./main');
const ecommerceUrl = "https://ecommerce-playground.lambdatest.io/";
class AddToCart extends Main {
constructor() {
super();
this.url = ecommerceUrl;
this.categoryButton = ('//a[normalize-space()="Shop by Category"]');
this.phonesCategoryButton = ('//span[normalize-space()="Phone, Tablets & Ipod"]');
this.iPhoneButton = ('//div[@class="carousel-item active"]//img[@title="iPhone"]');
this.addToCartButton = ('//div[@id="entry_216842"]//button[@title="Add to Cart"][normalize-space()="Add to Cart"]');
this.cartButton = ('//a[@class="btn btn-primary btn-block"]');
this.itemNameText = ('//td[@class="text-left"]//a[contains(text(),"iPhone")]');
}
async visit() {
await this.driver.get(this.url);
}
async before() {
this.driver;
}
async quitB() {
await this.driver.quit();
}
async categoryBtn() {
const categoryBtn = await this.byXpath(this.driver, this.categoryButton);
await categoryBtn.click();
}
async phonesCategoryBtn() {
const phonesCategoryBtn = await this.byXpath(this.driver, this.phonesCategoryButton);
await phonesCategoryBtn.click();
}
async iPhoneBtn() {
const HTCPhoneBtn = await this.byXpath(this.driver, this.iPhoneButton);
await HTCPhoneBtn.click();
}
async addToCartBtn() {
const categoryBtn = await this.byXpath(this.driver, this.addToCartButton);
await categoryBtn.click();
}
async cartBtn() {
const cartBtn = await this.byXpath(this.driver, this.cartButton);
await cartBtn.click();
}
async itemName() {
const itemName = await this.byXpath(this.driver, this.itemNameText);
itemName.getText().then(function (value) {
expect(value).toBe("iPhone");
});
}
}
module.exports = new AddToCart();
Code Walkthrough:
Variable Main is assigned the value of the Main class imported from the main.js file. Then, the variable ecommerceUrl is assigned the e-commerce website URL.
The child class of the parent class Main, called AddToCart, is created using the extends keyword. The AddToCart class will inherit all the methods from the Main class.
The AddToCart class constructor() method is created, using the super() method to call the constructor of the parent class Main. In the constructor method, this.url property is assigned the value of the variable ecommerceUrl.
Properties this.categoryButton, this.phonesCategoryButton, this.iPhoneButton, this.addToCartButton, this.cartButton, and this.itemNameText are assigned selector values that will be used to find or select buttons or text to add an item to a cart.
The async function visit() is created where the get() method is used to load the URL of the e-commerce store registration page.
The async functions before() and quitB() are created where the async function before() starts a browser session while the async function quitB() ends the browser session.
Async functions categoryBtn(), phonesCategoryBtn(), iPhonePhoneBtn(), addToCartBtn(), cartBtn(), and itemName() are created where the path for web elements, texts, and buttons to be tested when adding item to cart is defined.
Finally, the AddToCart class is exported to be used in other files.
Step 12: In the Tests folder, create a file called, mainTest.spec.js and add the following code.
const addToCart = require("../pageModel/addToCart.main");
//to set jasmine default timeout
jasmine.DEFAULT_TIMEOUT_INTERVAL = 80 * 1000;
jasmine.getEnv().defaultTimeoutInterval = 800000;
// Start to write the first test case
describe("E-Commerce Site End-To-End Tests", function () {
beforeEach(async () => {
addToCart.before();
});
afterEach(async () => {
addToCart.quitB();
});
it("Add Item To Cart And Checkout", async function () {
await addToCart.visit();
// Add to cart
await addToCart.categoryBtn();
await addToCart.phonesCategoryBtn();
await addToCart.iPhoneBtn();
await addToCart.addToCartBtn();
await addToCart.cartBtn();
await addToCart.itemName();
});
});
Code Walkthrough:
Variable addToCart is assigned the value of the AddToCart class imported from the addToCart.main.js file.
The default timeout interval for tests is set.
The jasmine.DEFAULT_TIMEOUT_INTERVAL = 80 * 1000 sets the default timeout interval to 80,000 milliseconds or 80 seconds. This means that if a test doesn't complete within 100 seconds, it will be marked as a failure.
The jasmine.getEnv().defaultTimeoutInterval = 80000 changes the default timeout interval to 60,000 milliseconds, or 60 seconds, after the initial default set in the previous line.
A describe block function called E-Commerce Site Automated Tests, where all the tests for the web application are written, is defined.
Inside the describe block, beforeEach and afterEach functions are created where they call before() and quitB() async functions created in the AddToCart class.
The beforeEach function is called before each test case is run and is used to set up the initial state or environment for the tests. The afterEach function is called after each test case is run, and it is used to clean up or reset the state of the environment after a test case is completed.
A test case called Add ItemTo Cart is defined.
The it function is used to define a single test case, and it takes two arguments: the first is a string that describes the test case, and the second is a function that contains the test logic.
Inside the test case, The visit() async function from the AddToCart class is called on the driver object, which is an instance of the Selenium WebDriver.
Async functions where the path for web elements, input fields, and buttons defined in the AddToCart class are called.
Step 13: Run the command below on the command line to run the tests.
npx jasmine spec/Tests/mainTest.spec.js
Once the commands run, you should see that the tests have passed successfully on your command line.
In this section of this tutorial on JavaScript automation testing, we will learn how to create and run a test script using the Jest framework.
Step 1: Run the command below on the command line to install Jest in your project. Adding --save-dev to the command helps save the name and version of Jest in the dev-dependency object.
npm install --save-dev jest
Step 2: Configure the npm test script to run the Jest tests when the command npm test is executed. To do that, update the package.json file and add a scripts section, as shown below.
"scripts": {
"test": "jest"
},
The package.json file code should now look as shown below.
{
"scripts": {
"test": "jest"
},
"devDependencies": {
"jest": "^29.7.0"
}
}
Step 3: Install the latest version of the Selenium WebDriver in the project folder by running the command below on the command line.
npm install selenium-webdriver
Your terminal line should look as shown below once the Selenium WebDriver is installed.
Step 4: Run the npm command below on the command line to install a Node.js JavaScript client for working with LambdaTest through Automation API.
npm i @lambdatest/node-rest-client
Step 5: In the JEST project folder, create a folder called Tests. Then, create a file called main.test.js in the Tests folder.
Step 6: Install dotenv package for managing environment variables using the command below.
npm install dotenv
Step 7: Create a file called .env in the main directory and add your LambdaTest username and access key, shown below.
LT_USERNAME="Your Username"
LT_ACCESS_KEY="Your Access Key”
Step 8: In the main.test.js file, add the following code.
const webdriver = require("selenium-webdriver");
const { until } = require("selenium-webdriver");
const { By } = require("selenium-webdriver");
const LambdaTestRestClient = require("@lambdatest/node-rest-client");
require("dotenv").config();
const username = process.env.LT_USERNAME;
const accessKey = process.env.LT_ACCESS_KEY;
const AutomationClient = LambdaTestRestClient.AutomationClient({
username,
accessKey,
});
const chromeWindowsCapability = {
browserName: "Chrome",
browserVersion: "105.0",
"LT:Options": {
username: username,
accessKey: accessKey,
platformName: "Windows 10",
project: "Untitled",
w3c: true,
plugin: "node_js-node_js",
},
};
const SafariMacosCapability = {
browserName: "Safari",
browserVersion: "16.0",
"LT:Options": {
username: username,
accessKey: accessKey,
platformName: "MacOS Ventura",
project: "Untitled",
w3c: true,
plugin: "node_js-node_js",
},
};
const firefoxWindowsCapability = {
browserName: "Firefox",
browserVersion: "106.0",
"LT:Options": {
username: username,
accessKey: accessKey,
platformName: "Windows 11",
project: "Untitled",
w3c: true,
plugin: "node_js-node_js",
},
};
const getElementById = async (driver, id, timeout = 8000) => {
const el = await driver.wait(until.elementLocated(By.id(id)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
const getElementByXpath = async (driver, xpath, timeout = 8000) => {
const el = await driver.wait(until.elementLocated(By.xpath(xpath)), timeout);
return await driver.wait(until.elementIsVisible(el), timeout);
};
// let sessionId = null;
describe("webdriver", () => {
let driver;
beforeAll(async () => {
driver = new webdriver.Builder()
.usingServer(
"https://" + username + ":" + accessKey + "@hub.lambdatest.com/wd/hub"
)
.withCapabilities(chromeWindowsCapability)
.build();
await driver.getSession().then(function (session) {
sessionId = session.id_;
});
// eslint-disable-next-line no-undef
await driver.get('https://ecommerce-playground.lambdatest.io/');
}, 50000);
afterAll(async () => {
await driver.quit();
}, 40000);
test("Add Item To Cart", async () => {
try {
const categoryBtn = await getElementByXpath(
driver,
'//a[normalize-space()="Shop by Category"]'
);
await categoryBtn.click();
const phonesCategoryBtn = await getElementByXpath(
driver,
'//span[normalize-space()="Phone, Tablets & Ipod"]'
);
await phonesCategoryBtn.click();
const iPhoneBtn = await getElementByXpath(
driver,
'//div[@class="carousel-item active"]//img[@title="iPhone"]'
);
await iPhoneBtn.click();
const addToCartBtn = await getElementByXpath(
driver,
'//div[@id="entry_216842"]//button[@title="Add to Cart"][normalize-space()="Add to Cart"]'
);
await addToCartBtn.click();
const cartBtn = await getElementByXpath(
driver,
'//a[@class="btn btn-primary btn-block"]'
);
await cartBtn.click();
const itemName = await getElementByXpath(
driver,
'//td[@class="text-left"]//a[contains(text(),"iPhone")]'
);
itemName.getText().then(function (value) {
expect(value).toBe("iPhone");
});
await updateJob(sessionId, "passed");
} catch (err) {
await updateJob(sessionId, "failed");
await webdriverErrorHandler(err, driver);
throw err;
}
}, 100000);
});
async function webdriverErrorHandler(err, driver) {
console.error("Unhandled exception! " + err.message);
if (driver && sessionId) {
try {
await driver.quit();
} catch (_) {}
await updateJob(sessionId, "failed");
}
}
function updateJob(sessionId, status) {
return new Promise((resolve, reject) => {
AutomationClient.updateSessionById(
sessionId,
{ status_ind: status },
(err) => {
if (err) return reject(err);
return resolve();
}
);
});
}
Code Walkthrough:
Selenium WebDriver, until, By and LambdaTest Rest Client are imported using require function.
A new automation client instance called AutomationClient with LambdaTest credentials is created.
Test capabilities are configured by passing browser, browser version, and operating system information with LambdaTest Selenium Grid capabilities through the capabilities object.
An async function called getElementById with parameters driver, id and timeout set to 2000 milliseconds are declared.
An async function called getElementByXpath with parameters driver, xpath and timeout set to 2000 milliseconds is declared.
A describe block function called Ecommerce Site Automated Test, where all the tests for the e-commerce website are defined.
Inside the describe block, a variable called driver is declared, and a beforeAll() Jest method is created where it takes two parameters which are a function and timeout.
In the code above, the beforeAll() method runs a function before any of the tests in a file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests. You can provide a timeout in milliseconds to specify how long to wait before aborting.
A new instance of a driver is created using the new webDriver.Builder() constructor.
A usingServer() method defines the remote URL for all builder instances created where the URL should be fully qualified for a WebDriver server.
A withCapabilities() method is created that sets the desired capabilities when requesting a new session. In this case, the withCapabilities() method takes the desired capabilities stored in the chromeWindowsCapability, safariMacosCapability, and firefoxWindowsCapability variables declared earlier.
A build() method that generates an action that contains all the actions gathered and ready to be performed is created.
An instance method called getSession() that returns a promise for a session is created.
A get() method opens the browser and navigates to the page URL you specify inside the method’s parentheses is created.
A afterAll() Jest method that takes two parameters which are function and timeout, is created.
A test block function called Add Item To Cart containing tests we want to run is created.
Inside the test block, a JavaScript try and catch statement is created.
Inside the try block, the path for web elements, input fields, and buttons on the e-commerce website we want to be tested is defined.
An async function called webdriverErrorHandler below the describe block with two parameters err, and the driver is created. Inside the async function, the error() method, which writes an error message to the console, is used.
A function called updateJob with parameters sessionId and status is created. Inside the function, a JavaScript Promise object is created.
Step 9: Run the command below on the command line to run the tests.
npm test main.test.js
Once the command completes running, you should see on the command line that the tests have passed, as shown below.
In this section of this tutorial on JavaScript automation testing, we will learn how to create and run a test script using the Mocha framework.
Step 1: Run the command below on the command line to install Mocha in your project.
npm i mocha
Step 2: Install the latest version of the Selenium WebDriver in the project folder by running the command below on the command line.
npm install selenium-webdriver
Step 3: Run the command below on the command line to install cross-env, so you can have a single command without worrying about setting or using the environment variable properly for your project.
npm i cross-env
Step 4: Configure the npm test script to run the Mocha tests when the command npm test is executed. To do that, update the package.json file and add a script section, as shown below.
"scripts": {
"test": "npm run single",
"single": "cross-env CONFIG_FILE=single ./node_modules/.bin/mocha specs/addToCart.js conf/addToCart.conf.js"
},
The package.json file code should now look as shown below.
{
"scripts": {
"test": "npm run single",
"single": "cross-env CONFIG_FILE=single ./node_modules/.bin/mocha specs/addToCart.js conf/addToCart.conf.js"
},
"dependencies": {
"cross-env": "^7.0.3",
"mocha": "^10.2.0",
"selenium-webdriver": "^4.15.0"
}
}
Step 5: Create two folders called Conf and Specs in the Mocha project folder, as shown below.
Step 6: In the Conf folder, create a file called addToCart.conf.js and add the following code.
LT_USERNAME = process.env.LT_USERNAME || "Username";
LT_ACCESS_KEY = process.env.LT_ACCESS_KEY || "accessKey";
exports.capabilities = {
'build': 'Mocha-Selenium', //Build name
'name': 'Add To Cart', // Test name
'platform':'Windows 10', // OS name
'browserName': 'chrome', // Browser name
'version': 'latest', // Browser version
};
The code above sets up configuration object capabilities with specific settings for running tests on LambdaTest with Mocha JavaScript.
Step 7: In the Specs folder, create a file called addToCart.js and add the following code.
var assert = require("assert"),
webdriver = require("selenium-webdriver"),
conf_file = process.argv[3] || "conf/addToCart.conf.js";
var caps = require("../" + conf_file).capabilities;
var buildDriver = function(caps) {
return new webdriver.Builder()
.usingServer(
"http://" +
LT_USERNAME +
":" +
LT_ACCESS_KEY +
"@hub.lambdatest.com/wd/hub"
)
.withCapabilities(caps)
.build();
};
describe("Ecommerce Automated Tests", function() {
var driver;
this.timeout(0);
beforeEach(function(done) {
caps.name = this.currentTest.title;
driver = buildDriver(caps);
done();
});
it("Add To Cart Test", function(done) {
driver.get("https://ecommerce-playground.lambdatest.io/").then( function() {
setTimeout(function() {
driver.findElement(webdriver.By.xpath('//a[normalize-space()="Shop by Category"]')).click()
driver.findElement(webdriver.By.xpath('//a[normalize-space()="Shop by Category"]')).click()
driver.findElement(webdriver.By.xpath('//a[normalize-space()="iPhone"]')).click()
driver.findElement(webdriver.By.xpath('//div[@id="entry_216842"]//button[@title="Add to Cart"][normalize-space()="Add to Cart"]')).click()
driver.findElement(webdriver.By.xpath('//a[@class="btn btn-primary btn-block"]')).click()
driver.findElement(webdriver.By.xpath('//td[@class="text-left"]//a[contains(text(),"iPhone")]')).click()
done();
}, 10000);
});
});
afterEach(function(done) {
if (this.currentTest.isPassed()) {
driver.executeScript("lambda-status=passed");
} else {
driver.executeScript("lambda-status=failed");
}
driver.quit().then(function() {
done();
});
});
});
Code Walkthrough:
The assert module for assertions and selenium-webdriver module are imported. Then process.argv is used to retrieve the configuration file path from the command line arguments, defaulting to "conf/addToCart.conf.js" if not provided.
The capabilities object from the specified configuration file conf/addToCart.conf.js is loaded.
A function buildDriver that creates a new WebDriver instance with LambdaTest server configuration and the specified capabilities is defined.
A test suite called Ecommerce Automated Tests is described using a describe block.
A beforeEach function that sets the test name in the capabilities and builds a new WebDriver instance before each test is defined.
A test case called Add To Cart Test is created using an it block.
Inside it block, the path for web elements on the e-commerce website we want to be tested is defined.
An afterEach function to be executed after each test is defined. If the test is passed, the function sets a custom status attribute using JavaScript on the browser and then quits the WebDriver after the test is completed.
Step 8: Run the command below on the command line to run the tests.
npm test
Once the command completes running, you should see on the command line that the tests have passed, as shown below.
Visit your LambdaTest Dashboard, and on the right side of the screen, you should be able to see your recent tests, as shown below.
Click on one of the tests, and you will be redirected to the Automation Dashboard, as shown below.
The Automation Dashboard has all the information about the test, including a video and a screenshot showing how the test went. You can also access the report on the Analytics Dashboard, which displays all the details and metrics related to your tests.
To see all the details and metrics related to your tests, navigate to the Analytics Dashboard, and you will be prompted to select an analytics template, as shown below.
In this case, you can select the Tests Summary Report template that provides all the summaries of the tests run on the LambdaTest Cloud Selenium Grid. On the right side of your page, you are prompted to create a dashboard where the test analytics will be displayed.
The first thing you need to do is give the dashboard a name. In this case, you can name the dashboard JasmineSeleniumE2E, as shown below.
Then filter the web automation reports you want to be displayed on the JasmineSeleniumE2E dashboard. In this case, you can filter the reports by Projects and then add the Projects, as shown below.
Finally, click the Create New Dashboard button at the bottom. You will then be redirected to the Test Summary report, as shown below.
Whether you're a developer or a tester aiming to enhance your skills as a JavaScript automation tester, join the Selenium JavaScript 101 certification program to strengthen your JavaScript expertise. This certification offers a solid groundwork, enabling you to effectively leverage Selenium JavaScript in testing endeavors and advance in your JavaScript automation testing journey.
In conclusion, you can use JavaScript automation testing to write and maintain tests. By using automation testing frameworks like Jest, Jasmine, Mocha, Cypress, Playwright and web automated testing platforms like LambdaTest Cloud Selenium Grid, you can ensure a web application performs as expected when accessed by users.
By leveraging the scalable infrastructure and extensive browser and device coverage provided by LambdaTest, you can execute tests in parallel across multiple environments, ensuring the optimal performance and compatibility of your web applications. Additionally, the seamless integration between these frameworks and LambdaTest simplifies the testing process, enabling you to efficiently identify and address any potential issues before they impact end users.
In essence, JavaScript automation testing, coupled with robust frameworks and web automated testing platforms, equips you with the tools and resources needed to maintain the integrity and functionality of your web applications. By embracing JavaScript automation testing practices, you can elevate the quality assurance process, minimize errors, and deliver exceptional user experiences that meet the evolving demands of today's digital landscape.
Did you find this page helpful?
Try LambdaTest Now !!
Get 100 minutes of automation test minutes FREE!!