I am having a huge problem with getting a unit test to work for a custom file directive for angular 1.5.0 and Jasmine 2.4, I have looked at
How to provide mock files to change event of <input type='file'> for unit testing
However this only seems to work for a raw input file field and not a custom directive.
First the directive, pretty straight forward model assignment. I also trigger a outside function on the scope which I make sure is in the unit test and don't get any errors from that. I just for the life of me can't force a change event to happen on the file input.
app.directive('fileModel', fileModel); fileModel.$inject = ['$parse', '$log']; function fileModel ($parse, $log) { return { restrict: 'A', link: function(scope, element, attrs) { var model = $parse(attrs.fileModel); var modelSetter = model.assign; element.bind('change', function(){ scope.$apply(function(){ modelSetter(scope, element[0].files); scope.parseFolder(scope.myFolder); }); }); } }; }
Here is the unit test, right now I am trying to trigger and event via a button because I couldn't get a manual event trigger to happen but that isn't working either.
describe('fileModel', function () { var $compile, $rootScope, directiveElem; beforeEach(module("LocalModule")); beforeEach(function(){ inject(function(_$compile_, _$rootScope_){ $compile = _$compile_; $rootScope = _$rootScope_; }); directiveElem = getCompiledElement(); }); function getCompiledElement(){ var element = angular.element('<div ng-controller="UploadCtrl as upload"><input id ="upload" type="file" file-model="myFolder"/><button type="button" id="button" ng-click="clickUpload()">Upload</button></div>'); var compiledElement = $compile(element)($rootScope); $rootScope.clickUpload = function(){ angular.element('#upload').trigger('click'); }; $rootScope.$digest(); return compiledElement; } it('should have input element', function () { var inputElement = directiveElem.find('input'); expect(inputElement).toBeDefined(); }); it('watched the change function', function () { var file = { name: "test.png", size: 500001, type: "image/png" }; var fileList = { 0: file, length: 1, item: function (index) { return file; } }; var inputElement = directiveElem.find('input'); var buttonElement = directiveElem.find('#button'); inputElement.files = fileList; directiveElem.triggerHandler({ type: 'change', target: { files: fileList } }); $rootScope.$digest(); buttonElement.triggerHandler('click'); }); });