Unit Testing AngularJs & Firebase: part 2

It’s good practice to test your controllers while developing, in this tutorial I used the following testing frameworks.

  • Mocha
  • Sinon
  • and Chai

Am using Firebase Angular library Angularfire, and used the CDN version of Firebase.js.

//index.html
<!DOCTYPE html>
<html lang=”en” ng-app=”app”>
<head>
<meta charset=”UTF-8">
<meta name=”viewport” content=”width=device-width, initial-scale=1.0">
<meta name=”author” content=”Victor Nwaokocha”>
<title>Murdeocrity</title>
<script src=”https://www.gstatic.com/firebasejs/3.4.0/firebase.js"></script>
<script>
var config = {
apiKey: “***”,
authDomain: “***”,
databaseURL: “***”,
storageBucket: “***”,
messagingSenderId: “***”
};
firebase.initializeApp(config);
</script>
<base href=”/”>
</head>
<body>
<app></app>
<script src=”bundle.js”></script>
</body>
</html>

Note that I’ve used Webpack, to bundle all the client assets. Also bundled all spec files, with Webpack require.context.

//spec.bundle.js
import angular from ‘angular’;
import mocks from ‘angular-mocks’;
let context = require.context(‘./client’, true, /\.spec\.js/);
context.keys().forEach(context);

and configured karma like this

//karma.conf.js
…..
frameworks: [‘mocha’, ‘chai’, ‘sinon’],
files: [
{ pattern: ‘spec.bundle.js’, watched: false }
],
…..

In the documentation for AngularFire, getting started involves, injecting the AngularFire Module.

import angular from ‘angular’;
import angularfire from ‘angularfire’;
angular.module(‘app’, [“firebase”])
.factory(‘Companies’, [‘$firebaseArray’, ($firebaseArray) => {
let ref = firebase.database().ref(‘companies/’);
return $firebaseArray(ref);
}]);

Injecting the factory in the controller.

//charts.controller
class ChartsController {
constructor(Companies, $log) {
this.companies = Companies;
Companies.$loaded().then(() => {
$log.log(“Firebase::”, “Companies data loaded!”);
});
}
}
ChartsController.$inject = [“Companies”, “$log”];
angular.module(‘app’).controller(“ChartController”, ChartController);

Finally testing the controller.

//charts.controller.spec.js
import {ChartsController} from ‘./charts.controller’;
describe(‘Charts’, () => {
let $rootScope;
let $q;
let makeController;
let CompaniesService = {
$loaded: function () {
return $q.defer().promise;
},
$getRecord: function () {
return [];
}
}
beforeEach(window.module(charts.name));
beforeEach(inject((_$rootScope_, _$q_) => {
$rootScope = _$rootScope_;
$q = _$q_;
makeController = (injectables) => {
return new ChartsController(injectables);
};
}));
describe(‘controller’, ()=> {
let controller;
it(‘should get ratings record form firebase’, ()=> {
sinon.spy(CompaniesService, ‘$loaded’);
controller = makeController(CompaniesService);
assert(RatingsService.$loaded.calledOnce);
});
});
});