我创建了一个指令“generate-form-field-directive”,它将根据收到的类型创建一个表单字段。以下是指令的代码 -
(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为“String”,则将呈现第一个输入标记。对于attributeDetails.type = integer也是如此。现在我想检查当我传递obkecj时属性中是否存在“input [type = text]” - 属性:{ “类型”:“字符串” “名字”:“名字”, “价值”:“第1卷” }。
单元测试文件是 -
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 :(得分:1)
运行此代码后:
element = $compile(template)($scope);
您应该能够找到您的输入:
var input = element[0].querySelector("input[type=text]");