Test Events in Angular
This is a test script to try to test Angular event handling.
HTML
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
var myApp = angular.module('myApp', []);
myApp.controller('mainCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
$scope.tDate = null;
$scope.sendEvent = function () {
// This function manipulates the date
// but for simplicity we will just send a string.
$scope.tDate = '2015-03-20T10:00:05';
if ($scope.tDate !== null) {
$scope.$broadcast('sendTime');
}
};
}]);
myApp.controller('subCtrl', ['$scope', '$rootScope', function ($scope, $rootScope) {
$scope.currentTime=null;
$scope.$on('sendTime', function() {
$scope.currentTime = "example";
});
}]);
describe('Test Events', function () {
var mainController, subController, mainScope, subScope, rootScope;
beforeEach(function () {
module('myApp');
inject(function ($controller, $rootScope) {
rootScope = $rootScope;
mainScope = $rootScope.$new();
subScope = $rootScope.$new();
spyOn(rootScope, '$broadcast').andCallThrough();;
spyOn(rootScope, '$on').andCallThrough();
mainController = $controller('mainCtrl', {
$scope: mainScope
});
subController = $controller('subCtrl', {
$scope: subScope
});
});
});
it('Should broadcast event.', function () {
mainScope.sendEvent();
var tDate = '2015-03-20T10:00:05';
expect(rootScope.$broadcast).toHaveBeenCalledWith('sendTime');
});
it('Should listen for event.', function () {
expect(rootScope.$on).toHaveBeenCalledWith('sendTime', jasmine.any(Function));
var time_result;
rootScope.$on('sendTime', function() {
time_result = "example";
});
rootScope.$emit('sendTime', 'example');
rootScope.$digest();
expect(time_result).toBe('example');
});
});
// --- Runner...