var navigationButtonsModule = angular.module('navigationButtonsModule', ['ui.router']);
navigationButtonsModule.config(['$stateProvider',
function($stateProvider) {
$stateProvider.state('home', {
url: '/home',
templateUrl: 'home.html'
});
}
]);
navigationButtonsModule.directive('navigationButton', function() {
return {
restrict: 'AE',
scope: {
state: "=?",
name: "=?"
},
template: '<button class="btn btn-success" ui-sref="{{state}}">Go to {{name}}</button>',
};
});
describe('directive: navigationButton', function() {
beforeEach(module('navigationButtonsModule'));
beforeEach(inject(function($rootScope, $compile, $state, $templateCache, $timeout) {
this.$rootScope = $rootScope;
this.$compile = $compile;
this.$state = $state;
this.$templateCache = $templateCache;
this.$timeout = $timeout;
this.testContainer = document.getElementById('test-container');
this.compileDirective = function(template, scope) {
var element = this.$compile(template)(scope);
this.testContainer.appendChild(element[0]);
scope.$digest();
return element;
}
}));
afterEach(function() {
this.testContainer.innerHTML = '';
});
it('navigation button should show passed name and ui-sref state', function() {
var template = '<navigation-button state="state" name="name"></navigation-button>';
var scope = this.$rootScope.$new();
scope.state = 'home';
scope.name = 'Home';
var element = this.compileDirective(template, scope);
expect(element.text()).toBe('Go to Home');
expect(element.find('button').attr('ui-sref')).toBe('home');
});
it('will show home href', function() {
expect(this.$state.href('home')).toEqual('#/home');
});
it('on button click browser should go to home state', function() {
var template = '<navigation-button state="state" name="name"></navigation-button>';
var scope = this.$rootScope.$new();
scope.state = 'home';
scope.name = 'Home';
var element = this.compileDirective(template, scope);
// mimicking home.html template
this.$templateCache.put('home.html', '');
this.$timeout(function() {
element.find('button')[0].click();
});
this.$timeout.flush();
this.$rootScope.$digest();
expect(this.$state.current.name).toBe('home');
});
});
<!-- jasmine -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine-html.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/boot.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.2.1/jasmine.min.css" rel="stylesheet" />
<!-- angular -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular-mocks.js"></script>
<div id="test-container"></div>