Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a text file in an Angular 8 unit test

I've have written a angular 8 application and planning to write unit test. Especially I need to test a file parser I have developed.

How do I read a text file, which is my golden model, from a unit test?

like image 300
lg.lindstrom Avatar asked Jan 20 '26 06:01

lg.lindstrom


1 Answers

Assumptions:

  • You're using Jasmine with Karma.
  • The method to be tested is KicadReader#read(url: string, dataHandler: DataHandler), DataHandler being some custom interface or class.
  • Your test file is src/app/shared/services/reader/kicad/test.sch.

This could be done with XMLHttpRequest as follows:

it('#read should supply Kicad file content', (done) => {

    // given
    const filePath = 'src/app/shared/services/reader/kicad/test.sch';
    const request: XMLHttpRequest = createRequest(filePath );

    request.onload = r => {
        const url = URL.createObjectURL(new Blob([request.response]));

        // when
        kicadReader.read(url, dataHandler);
    };

    dataHandler.onData = data => {

        // then
        expect(data).toBe('expected data');
        done();
    };

    // trigger
    request.send(null);
});

function createRequest(filePath: string): XMLHttpRequest {
    const request = new XMLHttpRequest();
    request.open('GET', 'base/' + filePath, true);
    request.responseType = 'arraybuffer'; // maybe also 'text'
    return request;
};

To make this work, Karma needs to be told to serve the test file (see http://karma-runner.github.io/4.0/config/files.html). To do so, add the following to your karma.config.js:

files: [
      { pattern: 'src/app/shared/services/reader/kicad/test.sch', included: false, watched: false, served: true }
]
like image 63
uminder Avatar answered Jan 22 '26 19:01

uminder