AI Features

Mocha: A JavaScript-Based Test Framework

Build on the fundamentals of Selenium by learning Mocha framework.

We'll cover the following...

Test syntax framework

Selenium scripts are different from Selenium tests. Selenium scripts are just pieces of code for driving the web browsers. On the other hand, Selenium tests drive the web browser as well as maintain a proper structure. In addition to this, Selenium tests provide assertions (performs checks on test scripts). To make effective use of Selenium scripts, we need to put them in the test framework first.

A test syntax framework is a framework that defines the structure of a test and it provides assertions based on that test.

Mocha test framework

Several JavaScript test frameworks are available in the market, and the most popular ones include Mocha, Karma, and Jasmine. For this course, we will use the Mocha test framework. Keep in mind, however, that any other JavaScript test framework would also work fine. Selenium techniques are applicable regardless of the syntax frameworks.

Consider the following Selenium script with Mocha framework (executable here) for user sign-in:

var webdriver = require('selenium-webdriver');
var test = require('selenium-webdriver/testing'); // add 'test.' wrapper
var driver = new webdriver.Builder()
.forBrowser('chrome')
.build();
var assert = require('assert');
test.describe('User Authentication', function () {
test.it('User can sign in', function () {
driver.get('http://travel.agileway.net');
driver.findElement(webdriver.By.name('username')).sendKeys('agileway');
driver.findElement(webdriver.By.name('password')).sendKeys('testwise');
driver.findElement(webdriver.By.name('commit')).click();
driver.getTitle().then( function(the_title){
assert.equal("Agile Travel", the_title);
});
});
});
Selenium test script for sign-in using Mocha framework

Here, the keywords, describe and it, are provided by selenium-webdriver/testing module, and define the structure of Mocha tests. I have used test.describe and test.it in the above code, which wait for the promise to resolve before resuming the function.

  • test.describe

    Description of a collection of related test cases.

  • test.it

    An individual test case.

Furthermore, I have used Node.js’ assert module ('assert.equal()') to perform checks in the above code as well.

Ask