gpt4 book ai didi

javascript - Angular Karma Jasmine - 测试功能

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:55 24 4
gpt4 key购买 nike

基本上我必须测试下面这个函数,我正在从文本文件中读取

$window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dir) {
var path = 'somefile.txt';
dir.getFile(path, { create: true }, function (file) {
file.file(function (file) {
var reader = new FileReader();
reader.onloadend = function () {
resolve(this.result);
}
reader.readAsText(file);
});
}, error);
}, error);

我一直在编写读取文件的单元测试用例

describe('get data from file', function () {            

it('should read the files from the data', function () {
var syncFile = 'somefile.txt';

expect( ).toBe( );
});
});

如何为文件读取器编写读取文件的单元测试?PS:我是使用 karma 进行单元测试的新手

最佳答案

您不应直接使用 FileReader。将该行更改为

var reader = new $window.FileReader();

在您的测试中模拟 $window 并返回一个自定义的 FileReader 对象。然后对其进行测试。如下所示。

describe('get data from file', function () {

var $window, fileReader;

beforeEach(function () {

inject(function (_$window_) {
$window = _$window_;
});

fileReader = function () {
return {};
};

spyOn($window, "FileReader").and.returnValue(fileReader);
});

it('should read the files from the data', function () {
var syncFile = 'somefile.txt';

expect($window.FileReader).toHaveBeenCalled();
});
});

关于javascript - Angular Karma Jasmine - 测试功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45830994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com