I have developed a custom directive called "generate-form-field-directive" that dynamically generates a form field based on the type received. Here is the code snippet for the 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>"
};
}
}());
If the attributeDetails.type is "String", the first input tag will be rendered. Similarly, for attributeDetails.type = integer. Now, I want to verify whether the "input[type=text]" element is present in the DOM or not when passing the object - { "type":"String", "name": "Name", "value": "Volume1" }.
The unit test file is as follows -
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);
});
});
});
It would be greatly appreciated if you could provide a functional fiddle for this. Thank you in advance.