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?
Assumptions:
KicadReader#read(url: string, dataHandler: DataHandler), DataHandler being some custom interface or class.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 }
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With