Angular unit tests exercise solution
Angular unit tests exercise solution
by bryangrimes
HTML
<script src="https://jasmine.github.io/2.8/lib/jasmine.js"></script>
<script src="https://github.com/jasmine/jasmine/blob/master/lib/jasmine-core/jasmine-html.js"></script>
<link rel="stylesheet" href="https://jasmine.github.io/2.8/lib/jasmine.css">
<script src="https://code.angularjs.org/1.6.8/angular.js"></script>
<script src="https://code.angularjs.org/1.6.8/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
var myApp = angular.module('myApp', []);
myApp.service('mySrv', [function () {
// Converts name from camelCase to snake-case
this.camelToSnakeCase = function (camelCase) {
return camelCase.replace(/[A-Z]/g, function (match, pos) {
return (pos > 0 ? '-' : '') + match.toLowerCase();
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'mySrv', function ($scope, mySrv) {
$scope.name = 'angular-js';
$scope.setName = function (name) {
$scope.name = mySrv.camelToSnakeCase(name);
};
}]);
myApp.directive('myDrtv', function () {
return {
restrict: 'E',
scope: {
name : '='
},
// Better to externalize to templateUrl, this is for demonstration sake
template: '<div>Hello {{name}}</div>',
replace: false
};
});
// ---SPECS-------------------------
describe('mySrv', function () {
var service;
beforeEach(function () {
module('myApp');
inject(function (mySrv) {
service = mySrv;
});
});
it('transforms camelCase to snake-case', function () {
expect(service.camelToSnakeCase('ThisStringIsCamelCase')).toBe('this-string-is-camel-case');
});
it('retains does not change snake-case input', function () {
expect(service.camelToSnakeCase('this-is-snake')).toBe('this-is-snake');
});
it('does not add a dash to a work starting with upper case char', function () {
expect(service.camelToSnakeCase('Simple')).toBe('simple');
expect(service.camelToSnakeCase('Simple')).not.toBe('-simple');
});
});
describe('myCtrl', function () {
var controller,
mySrvSpy,
scope;
beforeEach(function () {
module('myApp');
mySrvSpy = jasmine.createSpyObj('mySrv', ['camelToSnakeCase']);
module(function ($provide) {
...