2013-05-03 11 views
6

Mój <custom-directive> ma replace:true i template: '<img />'. Jak mogę napisać test jednostkowy? Myślę, że chcę przetestować, czy faktycznie zastępuje on dyrektywę niestandardową img.AngularJS przetestuj dyrektywę z zamień na true

it('should be transformed to <img>', function(){ 
    var elm = $compile('<custom-directive></custom-directive>')(scope); 
    scope.$digest(); 

    var t = elm.find('img'); // wrong! it replaces the element. it won't find another one inside 
//expect(elm).toBeAnImgElement ? 
}); 

Nie mogę znaleźć poprawnego matchera. Najbliższy przypadek, jaki widziałem, to sprawdzenie zawartości (elm.html() lub elm.text()), ale mój tag jest pusty.

Odpowiedz

18

owinąć dyrektywę w div jak:

describe('Directive: custom', function() { 
    beforeEach(module('App')); 

    var element, $scope; 

    it('should be transformed to <img>', inject(function ($rootScope, $compile) { 
    $scope = $rootScope.$new(); 
    element = angular.element('<div><custom-directive></custom-directive></div>'); 
    element = $compile(element)($scope); 

    expect(element.children('img').length).toBe(1); 
    })); 
}); 
+0

Dlaczego musimy '$ rootScope $ Digest();' tutaj.? Rzeczywiście, bez niego nie działa, ale nie rozumiem dlaczego. – thorn

+0

@thorn: Tak, to nie jest wymagane. – codef0rmer

+0

Nie, jest. Jak napisałem, nie działa bez niego. – thorn

3

Można uzyskać rzeczywisty obiekt HTMLElement i sprawdzić jego nazwę. Dostać się do rzeczywistej HTMLElement z elm[0]:

expect(elm[0].tagName).toEqual('A'); 
Powiązane problemy