2013-05-03 4 views
6

मेरा <custom-directive>replace:true और template: '<img />' है। मैं इसके लिए यूनिट परीक्षण कैसे लिख सकता हूं? मुझे लगता है कि मैं परीक्षण करना चाहता हूं कि यह वास्तव में आईएमजी के साथ कस्टम-निर्देश को प्रतिस्थापित करता है।एंगुलरजेएस प्रतिस्थापन सेट के साथ एक निर्देश का परीक्षण सही

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 ? 
}); 

मुझे सही matcher नहीं मिल रहा है। मैंने देखा सबसे नज़दीकी मामला सामग्री की जांच कर रहा है (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

+0

@thorn: हाँ, यह आवश्यक नहीं है। – codef0rmer

+0

नहीं, यह है। जैसा कि मैंने लिखा है, यह इसके बिना काम नहीं करता है। – thorn

3

आप वास्तविक HTMLElement ऑब्जेक्ट प्राप्त कर सकते हैं और उसका टैगनाम देख सकते हैं। elm[0] के साथ वास्तविक HTMLElement पर प्राप्त करें:

expect(elm[0].tagName).toEqual('A'); 
संबंधित मुद्दे