Sunday, February 16, 2014

An example of use of Protractor with Mocha and Chai for an Angular applicaion

Protractor is for end to end or integration testing of an Angular JS application. Its from the user perspective testing the application. Don't get confused with Karma, Karma is for unit testing.

To make it more clear a directive or a module can be tested with Karma, but to test the whole application from end to end we need Protractor like framework.

Protractor is a wrapper around WebdriverJS. If you have heard about Selenium, then Selenium 2.0 is actually a combination of Selenium 1.0 and WebDriver API. Please follow the link to know more about it:

Mocha is a Javascript test  framework developed in Node.js framework:

Chai is an assertion library which provides lots of functionalities to create BDD/TDD based tests.It provides several libraries like Should, Assert and Expect.

I can explain each of these libraries, but this is not scope of my post, here I will explain how to install each of these and create a sample test file and run it successfully. Follow the steps for it:
First install Node.js then follow these steps:

1. npm install -g protractor

2. web-driver manager update

3. npm install -g mocha

4. npm install chai

5. npm install chai-as-promised

Lets create a simple AngularJS application which we will test:

var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function ($scope) {
    $scope.myName = "John";

<!doctype html>
    <script src=""></script>
    <script src="main.js"></script>
<div ng-app="my-app">
    <div ng-controller="my-ctrl">

Now let's create the test configuration for protractor:


exports.config = {
    framework: 'mocha',
    seleniumAddress: 'http://localhost:4444/wd/hub',
    specs: ['e2e_test.js']

Let's create the actual test script:

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
var expect = chai.expect;
//Give the URL to the actual URL where your Angular app is runningbrowser.get(';
var name = element(by.binding('myName'));

To run the test please use the following command:

 protractor protractortest_conf.js

Now you should able to see the results of the end to end testing of the application.     

Write comments
  1. nice post. :) I know it is weird for me to want to do this, but in Protractor can you get ahold of an Angular Service in a vacuum the way you would in a unit test? Thanks!

    1. Ideally there is no way to get ahold of Angular Service in Protractor.

  2. This comment has been removed by the author.