Skip to main content

Selenium with JestJS

Learn how to run your first Selenium Webdriver test with JestJS on BrowserStack Automate.

Important: Sample test scripts are available in the jest-js-browserstack repository.

The sample test script in this section is compatible with JSON wire protocol-based client bindings. Check out our W3C-based scripts in the selenium-4 branch of the repository.

Introduction

BrowserStack gives you instant access to our Selenium Grid of 3000+ real devices and desktop browsers. Running your Selenium tests with JestJS on BrowserStack is simple.

This guide will help you:

  1. Run your first test
  2. Understand the details of your test
  3. Mark tests as passed or failed
  4. Debug your app

Prerequisites

Run your first test

To run your first JestJS test on BrowserStack, complete the following steps:

Step 1: Clone the jest-js-browserstack sample repository on GitHub using the following command:

   git clone https://github.com/browserstack/jest-js-browserstack.git
   cd jest-js-browserstack

Step 2: Install the required dependencies in the sample repository by running the following command in your command-line:

    npm install

Step 3: Set your BrowserStack credentials in the jest-js-browserstack/conf/parallel.test.js file as follows:

parallel.test.js
   ...
   const username = YOUR_USERNAME;
   const accessKey = YOUR_ACCESS_KEY;
   ...

Alternatively, you can set the environment variables in your system as shown in the following snippet:

  # Set these values in your ~/.zprofile (zsh) or ~/.profile (bash)
    export BROWSERSTACK_USERNAME="YOUR_USERNAME"
    export BROWSERSTACK_ACCESS_KEY="YOUR_ACCESS_KEY"
  # setx.exe does not set the environment variable in the current command prompt, but it will be available in subsequent command prompts
    setx BROWSERSTACK_USERNAME="YOUR_USERNAME"
    setx BROWSERSTACK_ACCESS_KEY="YOUR_ACCESS_KEY"

Step 4: Run your first test with BrowserStack using the following command:

    npm run parallel
    # or
    yarn run parallel

Step 5: View your tests on BrowserStack on the BrowserStack Automate Dashboard.

Protip: You can use our capability builder and select from a wide range of custom capabilities that BrowserStack supports.

Understand the details of your test

Learn about how the different components of the test suite work together using the following information.

Understand your first test script

When you run the npm run parallel command, the parallel.test.js file within the jest-js-browserstack/src directory is executed. When the test is triggered, it:

  • Opens the bstackdemo.com website.
  • Adds a product to the cart.
  • Verifies whether the product is added to the cart.
  • Marks the test as passed or failed based on whether the product is available in the cart.
src/parallel.test.js
  const { Builder, By, Key, until } = require("selenium-webdriver");
  const https = require("https");
  const capabilities = require("../conf/parallel.conf");

  const createDriver = async (capabilities) => {
    let driver = await new Builder()
      .usingServer("https://hub.browserstack.com/wd/hub")
      .withCapabilities(capabilities)
      .usingHttpAgent(
        new https.Agent({
          keepAlive: true,
          keepAliveMsecs: 1000000,
        })
      )
      .build();

    if (
      !capabilities.realMobile &&
      !capabilities["bstack:options"] &&
      !capabilities["bstack:options"].realMobile
    ) {
      await driver.manage().window().maximize();
    }

    return driver;
  };

  const setStatusAndKillDriver = async (driver, statusFail) => {
    if (driver) {
      await driver.executeScript(
        `browserstack_executor: ${JSON.stringify({
          action: "setSessionStatus",
          arguments: {
            status: statusFail ? "failed" : "passed",
            reason: statusFail ? statusFail : "",
          },
        })}`
      );
      await driver.quit();
    }
    if (statusFail) throw statusFail;
  };

  describe.each(capabilities)("BStack demo test on %j", (capabilities) => {
    test.concurrent(
      "login test",
      async () => {
        capabilities["bstack:options"].sessionName =
          "login - parallel test " +
          (capabilities["bstack:options"].deviceName || capabilities.browserName);
        let statusFail;
        let driver = await createDriver(capabilities);
        try {
          await driver.get("https://bstackdemo.com");

          await driver.findElement(By.css("#signin")).click();

          await driver.wait(until.elementLocated(By.css("#username input")));

          await driver
            .findElement(By.css("#username input"))
            .sendKeys("locked_user", Key.ENTER);

          await driver
            .findElement(By.css("#password input"))
            .sendKeys("testingisfun99", Key.ENTER);

          await driver.findElement(By.css("#login-btn")).click();

          await driver.wait(until.elementLocated(By.css(".api-error")));

          expect(await driver.findElement(By.css(".api-error")).getText()).toBe(
            "Your account has been locked."
          );
        } catch (e) {
          statusFail = e.message;
        } finally {
          await setStatusAndKillDriver(driver, statusFail);
        }
      },
      10000000
    );

    test.concurrent(
      "add products to cart",
      async () => {
        capabilities["bstack:options"].sessionName =
          "add products to cart - parallel test " +
          (capabilities["bstack:options"].deviceName || capabilities.browserName);
        let statusFail;
        let driver = await createDriver(capabilities);

        try {
          await driver.get("https://bstackdemo.com/");
          await driver.wait(until.titleMatches(/StackDemo/i), 10000);

          // locating product on webpage and getting name of the product
          let productText = await driver
            .findElement(By.xpath('//*[@id="1"]/p'))
            .getText();
          // clicking the 'Add to cart' button
          await driver.findElement(By.xpath('//*[@id="1"]/div[4]')).click();
          // waiting until the Cart pane has been displayed on the webpage
          driver.findElement(By.className("float-cart__content"));
          // locating product in cart and getting name of the product in cart
          let productCartText = await driver
            .findElement(
              By.xpath(
                '//*[@id="__next"]/div/div/div[2]/div[2]/div[2]/div/div[3]/p[1]'
              )
            )
            .getText();
          // checking whether product has been added to cart by comparing product name
          expect(productText).toBe(productCartText);
        } catch (e) {
          statusFail = e.message;
        } finally {
          await setStatusAndKillDriver(driver, statusFail);
        }
      },
      10000000
    );
  });

Understand the JestJS configuration file

In the sample repository, the configuration file named parallel.conf.js exists in the jest-js-browserstack/conf directory of the project. It is preloaded with default configuration for connecting tests to BrowserStack, and sample capabilities, such as browser name and its version, for running tests.

parallel.conf.js
   require("dotenv").config();

    const username = process.env.BROWSERSTACK_USERNAME || "";
    const accessKey = process.env.BROWSERSTACK_ACCESS_KEY || "";
    const buildName =
      process.env.BROWSERSTACK_BUILD_NAME || `jest-browserstack Dt - ${Date.now()}`;

    module.exports = [
      {
        "bstack:options": {
          os: "Windows",
          osVersion: "11",
          local: "false",
          seleniumVersion: "4.1.0",
          projectName: "BStack Demo",
          buildName: buildName,
          sessionName: "parallel test - Chrome latest",
          userName: username,
          accessKey: accessKey,
        },
        browserName: "Chrome",
        browserVersion: "latest",
      },
      {
        "bstack:options": {
          os: "Windows",
          osVersion: "11",
          local: "false",
          seleniumVersion: "4.1.0",
          projectName: "BStack Demo",
          buildName: buildName,
          sessionName: "parallel test - Chrome latest-1",
          userName: username,
          accessKey: accessKey,
        },
        browserName: "Chrome",
        browserVersion: "latest-1",
      },
      {
        "bstack:options": {
          os: "OS X",
          local: "false",
          seleniumVersion: "4.1.0",
          projectName: "BStack Demo",
          buildName: buildName,
          sessionName: "parallel test - Safari latest",
          userName: username,
          accessKey: accessKey,
        },
        browserName: "Safari",
        browserVersion: "latest",
      },
      {
        "bstack:options": {
          osVersion: "15",
          deviceName: "iPhone 13",
          realMobile: "true",
          local: "false",
          seleniumVersion: "4.1.0",
          projectName: "BStack Demo",
          buildName: buildName,
          sessionName: "parallel test - iPhone",
          userName: username,
          accessKey: accessKey,
        },
        browserName: "iPhone",
      },
      {
        "bstack:options": {
          osVersion: "12.0",
          deviceName: "Google Pixel 6 Pro",
          realMobile: "true",
          local: "false",
          seleniumVersion: "4.1.0",
          projectName: "BStack Demo",
          buildName: buildName,
          sessionName: "parallel test - Android",
          userName: username,
          accessKey: accessKey,
        },
        browserName: "Chrome",
      },
    ];

Integrating your tests with BrowserStack

The parallel.test.js file includes configurations, such as the capabilities and browser-related information used to run the tests on BrowserStack as shown in the following code snippet:

src/parallel.test.js
...
  const { Builder, By, Key, until } = require("selenium-webdriver");
  const https = require("https");
  const capabilities = require("../conf/parallel.conf");

  const createDriver = async (capabilities) => {
    let driver = await new Builder()
      .usingServer("https://hub.browserstack.com/wd/hub")
      .withCapabilities(capabilities)
      .usingHttpAgent(
        new https.Agent({
          keepAlive: true,
          keepAliveMsecs: 1000000,
        })
      )
      .build();
...

Understand the dependencies

The required dependencies to run all the tests in the repository are added to the package.json file as shown in the following code snippet:

package.json
  "devDependencies": {
    "@types/jest": "^27.4.0",
    "jest": "^27.4.7"
  },
  "dependencies": {
    "browserstack-local": "^1.4.8",
    "dotenv": "^16.0.0",
    "selenium-webdriver": "4.1.0"
  },

Understand the command to run parallel test

The test file that will be used to run the parallel test is specified in the package.json file, as shown below:

package.json
    "scripts": {
      "test": "jest",
      "parallel": "jest src/parallel.test.js",
      ...
    }

Mark tests as passed or failed

BrowserStack provides a comprehensive REST API to access and update information about your tests. The following sample code snippet shows how you can mark your tests as pass or fail based on the assertions in your JestJS test cases.

var request = require("request");
request({
  uri: "https://YOUR_USERNAME:YOUR_ACCESS_KEY@api.browserstack.com/automate/sessions/<session-id>.json", 
  method:"PUT", 
  form:{
    "status":"<passed/failed>",
    "reason":"<Your reason goes here>"
  }
})
await driver.executeScript(
  `browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"<passed/failed>","reason": "<reason>"}}`
);

Debug your app

BrowserStack provides a range of debugging tools to help you quickly identify and fix bugs you discover through your automated tests. Learn more about how to debug tests on BrowserStack using the Automate Dashboard.

Text logs

Text Logs are a comprehensive record of your test. They are used to identify all the steps executed in the test and troubleshoot errors for the failed step. Text Logs are accessible from the Automate dashboard or via our REST API.

Visual logs

Visual Logs automatically capture the screenshots generated at every Selenium command run through your JestJS tests. Visual logs help with debugging the exact step and the page where failure occurred. They also help identify any layout or design related issues with your web pages on different browsers.

Visual Logs are disabled by default. In order to enable Visual Logs you will need to set browserstack.debug capability to true.

module.exports = {
  ...
  "browserstack.debug": "true",
  ...
}

Sample Visual Logs from Automate Dashboard: BrowserStack Automate Visual Logs

Video recording

Every test run on the BrowserStack Selenium grid is recorded exactly as it is executed on our remote machine. This feature is particularly helpful whenever a browser test fails. You can access videos from Automate Dashboard for each session. You can also download the videos from the Dashboard or retrieve a link to download the video using our REST API.

Note: Video recording increases test execution time slightly. You can disable this feature by setting the browserstack.video capability to false.

In addition to these logs BrowserStack also provides Raw logs, Network logs, Console logs, Selenium logs, Appium logs and Interactive session. You can find the complete details to enable all the debugging options.

Next steps

After you have successfully run your first test on BrowserStack, you might want to do one of the following:

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback

Is this page helping you?

Yes
No

We're sorry to hear that. Please share your feedback so we can do better

Contact our Support team for immediate help while we work on improving our docs.

We're continuously improving our docs. We'd love to know what you liked






Thank you for your valuable feedback!

Talk to an Expert
Talk to an Expert