2013-05-03 70 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');