Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Karma Jasmine - test function

Basically i have to test this below function, where i'm reading from 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'm stuck in writing the unit test cases for reading 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 for reading the file? PS : i'm new to unit testing using karma

like image 544
Matarishvan Avatar asked Aug 23 '17 05:08

Matarishvan


People also ask

What is Jasmine in Angular testing?

Angular ships with Jasmine, a JavaScript framework that enables you to write and execute unit and integration tests. Jasmine consists of three important parts: A library with classes and functions for constructing tests. A test execution engine. A reporting engine that outputs test results in different formats.


1 Answers

You should not use FileReader directly. Change that line to

var reader = new $window.FileReader();

In your test mock the $window and return a custom FileReader object. Then do the tests on that. 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();
   });
});
like image 58
Shahzad Avatar answered Sep 18 '22 02:09

Shahzad