2013-05-03 67 views
6

我的<custom-directive>replace:truetemplate: '<img />'。 如何爲它編寫單元測試?我想我想測試它實際上是否將img替換爲自定義指令。AngularJS測試指令替換設置爲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 ? 
}); 

我找不到正確的匹配器。 我見過的最接近的案例是檢查內容(elm.html()elm.text()),但我的標籤是空的。

回答

18

包裹你的指令像一個div:

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

爲什麼我們需要'$ rootScope $摘要();'在這裏?事實上,沒有它,它就無法工作,但我不明白爲什麼。 – thorn 2014-04-30 09:57:23

+0

@thorn:是的,這不是必需的。 – codef0rmer 2014-04-30 17:29:27

+0

不,是的。正如我寫的,沒有它就沒有用。 – thorn 2014-04-30 17:46:13

3

您可以獲取實際的HTMLElement對象並檢查其標記名。在獲取與elm[0]實際的HTML元素:

expect(elm[0].tagName).toEqual('A');