Skip to main content

Selenium with Mocha JS

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

Important: Sample test scripts are available in the mocha-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 Mocha on BrowserStack is simple.

In this guide, you will learn about:

  1. Prerequisites
  2. Running your first test
  3. Understanding the details of your test
  4. Marking tests as passed or failed
  5. Debugging your app

Prerequisites

Run your first test

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

  1. Clone the mocha-browserstack sample repo on GitHub using the following command:

    git clone https://github.com/browserstack/mocha-browserstack.git
    cd mocha-browserstack
    
  2. Install the required dependencies by running the following command in your command line:

     npm install
    
  3. Set your BrowserStack credentials and browser/devices where you want to run your test in the mocha-browserstack/conf/parallel.conf.js file as follows:

    parallel.conf.js
     var config = {
       'commanCapabilities': {
         'browserstack.user': 'YOUR_USERNAME',
         'browserstack.key': 'YOUR_ACCESS_KEY',
         'build': 'mocha-browserstack',
         'name': 'parallel_test',
         'browserstack.debug': 'true',
       },
       'multiCapabilities': [{
           'os': 'Windows',
           'os_version': '10',
           'browserName': 'Chrome',
           'browser_version': 'latest',
           'name': 'Parallel test 1'
         },
         {
           'os': 'OS X',
           'os_version': 'Monterey',
           'browserName': 'Chrome',
           'browser_version': 'latest',
           'name': 'Parallel test 2'
         },
         {
           'os' : 'OS X',
           'os_version' : 'Big Sur',
           'browserName' : 'Safari',
           'name': 'Parallel test 3'
         },
         {
           'browserName': 'Android',
           'device': 'Samsung Galaxy S20',
           'realMobile': 'true',
           'name': 'Parallel test 4'
         },
         {
           'browserName': 'iPhone',
           'device': 'iPhone 12 Pro Max',
           'realMobile': 'true',
           'name': 'Parallel test 5'
       }]
     };
    
     exports.capabilities = [];
     // Code to support common capabilities
     config.multiCapabilities.forEach(function(caps) {
       var temp_caps = JSON.parse(JSON.stringify(config.commanCapabilities));
       for(var i in caps) temp_caps[i] = caps[i];
       exports.capabilities.push(temp_caps);
     });
    
  4. Run your first test using the following command:
     npm run parallel
    
  5. View your tests on BrowserStack on the BrowserStack Automate Dashboard.
Protip: You can use our capability builder and select from a 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 mocha-browserstack/specs 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.
parallel_test.js
var config = {
  'commonCapabilities': {
    'browserstack.user': process.env.BROWSERSTACK_USERNAME || 'BROWSERSTACK_USERNAME',
    'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY || 'BROWSERSTACK_ACCESS_KEY',
    'build': 'mocha-browserstack',
    'browserstack.debug': 'true',
  },
  'multiCapabilities': [{
      'os': 'Windows',
      'os_version': '10',
      'browserName': 'Chrome',
      'browser_version': 'latest',
      'name': 'Parallel test 1'
    },
    {
      'os': 'OS X',
      'os_version': 'Monterey',
      'browserName': 'Chrome',
      'browser_version': 'latest',
      'name': 'Parallel test 2'
    },
    {
      'os' : 'OS X',
      'os_version' : 'Big Sur',
      'browserName' : 'Safari',
      'name': 'Parallel test 3'
    },
    {
      'browserName': 'Android',
      'device': 'Samsung Galaxy S20',
      'realMobile': 'true',
      'name': 'Parallel test 4'
    },
    {
      'browserName': 'iPhone',
      'device': 'iPhone 12 Pro Max',
      'realMobile': 'true',
      'name': 'Parallel test 5'
  }]
};

exports.capabilities = [];
// Code to support common capabilities
config.multiCapabilities.forEach(function(caps) {
  var temp_caps = JSON.parse(JSON.stringify(config.commonCapabilities));
  for(var i in caps) temp_caps[i] = caps[i];
  exports.capabilities.push(temp_caps);
});

Understand the Mocha configuration file

In the sample repository, the configuration file named parallel.conf.js exists in the mocha-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
  var config = {
  'commonCapabilities': {
    'browserstack.user': process.env.BROWSERSTACK_USERNAME || 'BROWSERSTACK_USERNAME',
    'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY || 'BROWSERSTACK_ACCESS_KEY',
    'build': 'mocha-browserstack',
    'browserstack.debug': 'true',
  }

Integrate your tests with BrowserStack

After the configuration file is created, it is referenced in the parallel_test.js spec file. The capabilities and browser-related information in the configuration file is used to run the tests on BrowserStack as shown below:

parallel_test.js
var assert = require('assert'),
  webdriver = require('selenium-webdriver'),
  conf_file = process.argv[3] || 'conf/single.conf.js',
  parallel = require('mocha.parallel'),
  Promise = require('bluebird');

var capabilities = require('../' + conf_file).capabilities;

var buildDriver = function(caps) {
  return new webdriver.Builder().
    usingServer('https://hub.browserstack.com/wd/hub').
    withCapabilities(caps).
    build();
};

parallel('Tests ', function() {
  var driver, bsLocal;

  capabilities.forEach(function(caps) {

    it('can add items to cart', function (done) {
      buildDriver(caps).then(async function(driver) {
        await driver.get('https://bstackdemo.com/');
        await driver.wait(webdriver.until.titleMatches(/StackDemo/i), 10000);

        try {
          // locating product on webpage and getting name of the product
          let productText = await driver.findElement(webdriver.By.xpath('//*[@id="1"]/p')).getText();
          // clicking the 'Add to cart' button
          await driver.findElement(webdriver.By.xpath('//*[@id="1"]/div[4]')).click()
          // waiting until the Cart pane has been displayed on the webpage
          driver.findElement(webdriver.By.className('float-cart__content'))
          // locating product in cart and getting name of the product in cart
          let productCartText = await driver.findElement(webdriver.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
          assert(productText === productCartText);

          //marking the test as Passed if product has been added to the cart
          await driver.executeScript(
            'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"passed","reason": "Product has been successfully added to the cart!"}}'
          );
        } catch (e) {
          //marking the test as Failed if product has not been added to the cart
          console.log("Error:", e.message)
          await driver.executeScript(
            'browserstack_executor: {"action": "setSessionStatus", "arguments": {"status":"failed","reason": "Some elements failed to load."}}'
          );
        } finally {
          await driver.quit();
          done();
        }
      });
    });
  });
});

Understand the command to run parallel test

The test and configuration file to consider for running a parallel test is specified in the package.json file, as shown below:

mocha-browserstack/package.json
    "scripts": {
    "parallel": "./node_modules/.bin/mocha specs/parallel_test.js conf/parallel.conf.js --timeout=60000",
  },

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 allows you to mark your tests as pass or fail based on the assertions in your Mocha 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>"}})

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 Mocha 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. To enable Visual Logs, set the browserstack.debug capability to true.

exports.capabilities = {
  'browserstack.debug': true
}

Sample Visual Logs from Automate Dashboard: BrowserStack Automate Visual Logs

Video recording

Every test that runs on the BrowserStack Selenium grid is recorded as it is executed on our remote machine. This feature is beneficial 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 sessions. 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