Angular Karma Jasmine - test function

Basically I have to check this function below, where I read from a text file

$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); 

I am stuck in writing unit test cases to read a file

 describe('get data from file', function () { it('should read the files from the data', function () { var syncFile = 'somefile.txt'; expect( ).toBe( ); }); }); 

How to write unit test for filereader to read a file? PS: I'm new to karma unit testing

+5
source share
1 answer

You should not use FileReader directly. Change this line to

 var reader = new $window.FileReader(); 

In your test, flip the $ window and return your own FileReader object. Then run the tests. Something like below.

 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(); }); }); 
+6
source

Source: https://habr.com/ru/post/1271134/


All Articles