angularjs - 如何使用 Jasmine 测试指令中的 'ng-click' 事件

标签 angularjs jasmine karma-jasmine

我想用 Jasmine 测试 'ng-click' 事件,但我不知道如何

我的指令文件是这样的(headbarDirective.js):

 (function () {
        angular.module('app.widgets.homeHeadbar',[])
            .directive('homeHeadbar', homeHeadbar);

        function homeHeadbar() {
            return {
                restrict: 'EAC',
                replace: true,
                transclude: false,
                scope: {
                    name: '@',
                    role: '@',
                },
                templateUrl: 'app/widgets/headbar/headbarView.html',
                link: function(scope, ele, attrs) {
                    if (!scope.name) {
                        scope.logined = false;
                    } else {
                        scope.logined = true;
                    }
                    scope.logout = function() {
                        UserService.logout();
                        $location.path('/login');
                };
                }
            };
        }
    })();

我的模板文件是这样的(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>

我的测试文件是这样的(test.js):
describe('test the headbarDirective',function(){

    beforeEach(module('templates','app','app.widgets.homeHeadbar'));

    var scope,ele,compile,simpleHtml,UserService,location;

    beforeEach(inject(function(_$rootScope_,_$compile_,_UserService_,_$location_){
        compile = _$compile_;
        scope = _$rootScope_.$new();
        location = _$location_;
        UserService = _UserService_;
    }));

    it('test the logout click',function(){
        simpleHtml = '<home-headbar name="John" role=2></home-headbar>';
        ele = compile(angular.element(simpleHtml))(scope);
        scope.$digest();

        spyOn(UserService,'logout').and.callThrough();

        $(ele).find('.logout').click();
        scope.$digest();

        expect(UserService.logout).toHaveBeenCalled();
    });
});

并且测试失败,控制台 结果是这样的:
Chrome 43.0.2357 (Windows 7 0.0.0) test the headbarDirective test the logout cli
ck FAILED
        Expected spy logout to have been called.
            at Object.<anonymous> (C:/Users/IBM_ADMIN/desk/workspace/WaterFundWe
b/WebContent/test/unit/widgets/headbar/headbarDirective.js:48:30)
Chrome 43.0.2357 (Windows 7 0.0.0): Executed 11 of 11 (1 FAILED) (0 secs / 0.124
Chrome 43.0.2357 (Windows 7 0.0.0): Executed 11 of 11 (1 FAILED) (0.125 secs / 0
.124 secs)

表示尚未调用注销功能。
我的代码有问题吗?我如何测试 ng-click 事件?

最佳答案

让我测试一下是否适合您,请随时“运行代码片段”

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>

关于angularjs - 如何使用 Jasmine 测试指令中的 'ng-click' 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31263157/

相关文章:

angular - 在 Angular Directive(指令)单元测试中注入(inject)服务

javascript - Angularjs - Jasmine 范围变量在测试中未定义

Angularjs 从成功/错误和 promise 处理 ajax 有什么区别?

javascript - AngularJS 中发出事件后的返回值

javascript - 如何在 AngularJS 1.x 中对过滤器进行单元测试

javascript - beforeEach 每次测试都会被调用,而不是只调用一次

javascript - Jasmine 节点不等待主体完成

javascript - 期望返回值等于 $promise

html - 如何使用 ui-sref-active ="active"设置悬停状态等于 li clearfix 元素的事件状态

javascript - AngularJS 嵌套 ng-repeat 访问索引