2016-11-02 61 views
0

我已經創建了一個指令「generate-form-field-directive」,它將根據收到的類型創建一個表單字段。下面是指令代碼 -在單元測試中檢查指令中是否存在html元素

(function() { 
"use strict"; 

var app = angular.module("appModule"); 

app.directive("generateFormField", generateFormField); 

/*@ngInject*/ 
function generateFormField() { 

    return { 
     restrict: "E", 

     scope: { 
      attributeDetails: "=", 
      fieldName: "=" 
     }, 

     replace: false, 

     controller: function($scope, actionStore) { 
      var vm = this;     
     }, 

     template: "<div class='col-sm-9 generate-form-field-container'>" + 

        "<input type='text' class='form-control' name='{{fieldName}}' ng-if='attributeDetails.type === \"String\"' ng-model='attributeDetails.value' required>" + 
        "<input type='number' class='form-control' name='{{fieldName}}'' ng-if='attributeDetails.type === \"Integer\"' ng-model='attributeDetails.value' required>" + 
       "</div>" 

    }; 
} 

}()); 

所以,如果attributeDetails.type是「字符串」,那麼第一個輸入標籤將被渲染。相同的attributeDetails.type =整數。現在我想檢查DOM中是否存在「input [type = text]」,當我通過obkecj - 屬性時:「012」「type」:「String」, 「name」:「Name」, 「值「:」Volume1「 }。

單元測試文件 -

describe("UNIT DIRECTIVE: generateFormField", function() { 
"use strict"; 

// Angular injectables 
var $compile, $rootScope, $httpBackend, $q; 

// Module defined (non-Angular) injectables 
var $scope, generateFormField, actionStore; 

// Local variables used for testing 
var element, formRequestResponse, directiveScope, vm, template, getListOptions; 

// Initialize modules 
beforeEach(function() { 
    module("appModule"); 
}); 

beforeEach(function() { 

    inject(function (_$compile_, _$rootScope_, _$httpBackend_, _$q_, _actionStore_) { 
     $compile = _$compile_; 
     $rootScope = _$rootScope_; 
     $httpBackend = _$httpBackend_; 
     $q = _$q_; 
     $scope = $rootScope.$new();    
    }); 
}); 

describe("generateFormField unit testing", function() { 

    beforeEach(function() { 
     template = "<generate-form-field attribute-details='attribute' field-name='key'></generate-form-field>";    
     $scope.attribute = { 
      "type":"String", 
      "name": "Name", 
      "value": "Volume1" 
     }, 

     $scope.key = "volName"; 
     element = $compile(template)($scope);  

     directiveScope = element.find("generate-form"); 

     // Exercise SUT 
     $scope.$digest(); 
    }); 

    **//how to check for input[type=text]** 
    it("it should create input button of type='text'", function() { 
     //expect(element.html()).indexOf("type='text'").to.not.equal(-1); 
     //expect(element("input[type=text]").length).to.be(1); 
    }); 

}); 
}); 

這將是很好,如果你可以爲它工作的小提琴。提前致謝。

+0

做[我的回答](http://stackoverflow.com/a/40374135/2545680 ) 幫幫我? –

+0

@Maximus謝謝:) –

+0

不客氣,你可以接受它,如果它解決了你的問題) –

回答

1

運行此代碼後:

element = $compile(template)($scope); 

你應該能夠找到您的輸入:

var input = element[0].querySelector("input[type=text]");