模拟目录文件对象

时间:2015-07-18 21:11:02

标签: javascript html file dom directory

在JavaScript中,如何创建模拟目录的File(或Blob)对象?

在Chrome 43上,当我将图像文件拖入上传表单时,我得到了这个:

lastModified: 1426770718000
lastModifiedDate: Thu Mar 19 2015 06:11:58 GMT-0700 (PDT)
name: "Cornered.jpg"
size: 261343
type: "image/jpeg"
webkitRelativePath: ""

当我记录目录时,我得到了这个:

lastModified: 1426770841000
lastModifiedDate: Thu Mar 19 2015 06:14:01 GMT-0700 (PDT)
name: "contest"
size: 476
type: ""
webkitRelativePath: ""

唯一的区别似乎是缺少扩展名和空type

This answer介绍如何检测目录。我想模拟一个目录,这样我就可以为以下函数编写一个单元测试:

var isDirectory = function (blob, callback) {
    var reader = new FileReader();
    reader.addEventListener('load', function () {
        callback(false);
    });
    reader.addEventListener('error', function () {
        callback(true);
    });
    reader.readAsArrayBuffer(blob);
};

我试过传递一个new Blob([]),因为它还有一个type的空字符串,但callback仍然使用false调用。< / p>

1 个答案:

答案 0 :(得分:0)

如果您只想对该功能进行单元测试,那么您只需模拟JavaScript FileReader

    describe('isDirectory', function () {
        var OriginalFileReader,
            MockFileReader = function () {
                this.callbacks = {};
                mockFileReaderInstance = this;
            },
            mockFileReaderInstance;

        MockFileReader.prototype = {
            addEventListener: function (event, callback) {
                this.callbacks[event] = callback;
            },
            readAsArrayBuffer: angular.noop
        };

        beforeEach(function () {
            OriginalFileReader = window.FileReader;
            window.FileReader = MockFileReader;
        });
        afterEach(function () {
            window.FileReader = OriginalFileReader;
        });

        it('should indicate false when object is not a directory', function () {
            var spy = jasmine.createSpy('spy');

            fileUtilities.isDirectory({}, spy);
            mockFileReaderInstance.callbacks.load();

            expect(spy).toHaveBeenCalledWith(false);
        });

        it('should indicate true when object is a directory', function () {
            var spy = jasmine.createSpy('spy');

            fileUtilities.isDirectory({}, spy);
            mockFileReaderInstance.callbacks.error();

            expect(spy).toHaveBeenCalledWith(true);
        });
    });

当然,这对FileReader本身的内部运作做出了某些假设,但表面上它已经过浏览器制造商的测试,你可以认为它的工作方式与广告一样。