我有一个如下指令,它的功能是读取文件:
myapp.directive('onReadFile', function ($parse) {
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.onReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
加载文件的Html如下:
<input id="fileInput" name="fileInput" type="file" accept='.csv' on-read-file="showContent($fileContent)" />
我尝试编写单元测试以查看它是否可以成功解析文件内容,我写了一点然后卡住了。
describe.only('On Read File Directive Test', function () {
var el, scope, $rootScope, $compile, $parse;
beforeEach(module('somemoudle'));
beforeEach(function () {
inject([
'$compile',
'$rootScope',
'$parse',
function (_$compile, _$rootScope, _$parse) {
$compile = _$compile;
$rootScope = _$rootScope;
scope = $rootScope.$new();
$parse = _$parse;
}
]);
});
function loadDirective() {
var files = '<div></div>';
el = $compile(files)(scope);
$rootScope.$digest();
scope = el.isolateScope();
}
it('should load', function () {
loadDirective();
expect(el.length).to.equal(1);
});
});