2013-07-26 26 views
0

單元測試指令,我有以下jsbin http://jsbin.com/uvipos/1/edit,增加了類元素

用,增加了對。主動父元素的自定義指令,如果它包含的鏈接是鏈接到頁面我們對(自舉例如)。該指令工作得很好,但我正在努力弄清楚如何測試它。

的指令:

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

你是不是改變了路線,你編制的元素之後 - 在element = $compile(element)($rootScope);expect(element.hasClass('active')).toBe(true);之間,插入一條線,如$browser.url(envs[count++])和你得到的。

+0

非常感謝您對IRC的幫助。 '$ rootScope。$ broadcast('$ routeChangeSuccess');'編譯後修復它 – RyanHirsch