Ответ 1
Позвольте мне проверить, если для вас, пожалуйста, не стесняйтесь "запускать фрагмент кода"
angular.module('app.widgets.homeHeadbar', [])
.directive('homeHeadbar', function homeHeadbar($location, UserService) {
return {
restrict: 'EAC',
replace: true,
transclude: false,
scope: {
name: '@',
role: '@',
},
templateUrl: 'app/widgets/headbar/headbarView.html',
link: function(scope, ele, attrs) {
scope.logout = function() {
UserService.logout();
$location.path('/login');
};
}
};
});
describe('test the headbarDirective', function() {
var scope, el, $compile, $location, simpleHtml, UserService;
beforeEach(module('app.widgets.homeHeadbar'));
/* stub as I don't know implementations for UserService */
beforeEach(function() {
var _stubUserService_ = {
logout: jasmine.createSpy('UserService.logout')
};
angular.module('app.widgets.homeHeadbar')
.value('UserService', _stubUserService_);
});
beforeEach(inject(function($rootScope, $templateCache, _$compile_, _$location_, _UserService_) {
$templateCache.put('app/widgets/headbar/headbarView.html', [
'<nav>',
' <div>',
' <div class="navbar-right" ng-show="logined">',
' <div class="dib fr ml20">',
' <div class="user-name cwh">{{name}}</div>',
' <div class="user-position cgray">{{role}}</div>',
' </div>',
' <a class="logout" href="javascript:;" ng-click="logout()">Log Out</a>',
' </div>',
' </div>',
'</nav>'
].join(''));
$location = _$location_;
$compile = _$compile_;
scope = $rootScope.$new();
UserService = _UserService_;
}));
it('clicks on "logout" redirects to /login page', function() {
spyOn($location, 'path')
simpleHtml = '<home-headbar name="John" role=2></home-headbar>';
el = $compile(angular.element(simpleHtml))(scope);
scope.$digest();
el.find('.logout').click();
expect(UserService.logout).toHaveBeenCalled();
expect($location.path).toHaveBeenCalledWith('/login');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>