单元测试指令,用于向元素添加类

时间:2013-07-26 18:32:38

标签: unit-testing angularjs

我有以下jsbin http://jsbin.com/uvipos/1/edit

使用自定义指令将.active添加到父元素(如果它包含的链接是指向我们所在页面的链接(例如,用于引导))。该指令运行得很好,但我正在努力弄清楚如何测试它。

指令:

  app.directive('whenChildActive', ['$location', function ($location) {
    return {
      link: function postLink(scope, element, attrs) {
        scope.$on( '$routeChangeSuccess', function () {
          var literalLink = element.find('a').attr( 'href' );

          var currentPath = $location.path();
          var hashPath = '#' + currentPath;
          if ( currentPath === literalLink || hashPath === literalLink) {
            element.addClass( 'active' );
          } else {
            element.removeClass( 'active' );
          }
        });
      }
    };
  }]);

我的测试尝试:

describe('Directive: whenChildActive', function () {
  beforeEach(module('myNgApp'));

  var element;
  var envs = [
    'http://server/#/app',
  ], count = 0;

  beforeEach(inject(function($browser){
    $browser.url(envs[count++]);
  }));

  it('should add class when child href matches location', inject(function ($rootScope, $compile) {
    element = angular.element('<li when-child-active><a href="#/app">Some Text</a>/li>');
    element = $compile(element)($rootScope);

    expect(element.hasClass('active')).toBe(true);
  }));
});

我的测试失败了,我不确定为什么

1 个答案:

答案 0 :(得分:1)

您在编译元素后没有更改路线 - 在element = $compile(element)($rootScope);expect(element.hasClass('active')).toBe(true);之间,插入$browser.url(envs[count++])之类的行以及您获得的内容。