Testing angular directives with Jasmine 2.0
HTML
<script src="http://jasmine.github.io/2.0/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/2.0/lib/jasmine-html.js"></script>
<script src="http://jasmine.github.io/2.0/lib/boot.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/2.0/lib/jasmine.css">
<script src="https://code.angularjs.org/1.3.15/angular.js"></script>
<script src="https://code.angularjs.org/1.3.15/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
angular.module('myApp', [])
.factory('MyService', function () {
return {
handleMessage: function (event) {
console.log('handling message');
console.log(event.data);
}
}
})
.directive('messaging', function ($window, MyService) {
return {
link: function () {
MyService.handleMessage(event);
angular.element($window).on('message', function (event) {
MyService.handleMessage(event);
});
}
};
});
// ---SPECS-------------------------
describe('', function () {
var element,
MyService,
$window;
beforeEach(function () {
module('myApp');
element = angular.element('<div messaging></div>');
inject(function ($rootScope, $compile, _$window_, _MyService_) {
$window = _$window_;
MyService = _MyService_;
var scope = $rootScope.$new();
$compile(element)(scope);
scope.$digest();
});
});
it('should test that MyService.handleMessage is called after a message has been posted', function (done) {
spyOn(MyService, 'handleMessage').and.callFake(function () {
expect(MyService.handleMessage).toHaveBeenCalled();
done();
});
$window.postMessage('message', '*');
});
});
// --- Runner -------------------------
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function () {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
...