Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read File inside a Jasmine Karma test

I have a service which acts on a file uploaded. I have a function in the service which basically converts the uploaded(.xlxs) file into workbook. I would want to write test case for this particular function. (Not uploaded to server but just to browser) Can anyone suggest on how to access a test file(say test_something.xlxs) from inside the unit test scenario. I would want to read the file as a binary string and pass on the object to the service methods.

Unit testing framework i use is Karma + Jasmine for angular.

like image 900
sriram Avatar asked Sep 03 '25 04:09

sriram


1 Answers

It's a pain, because by the time you get into your harness, you're in sandboxed-browser-land and you can't really access external files easily. Karma works by basically creating a fake HTML page wrapper that it loads into a browser for testing, via PhantomJS, Jasmine, etc. By the time your test harness gets going, that browser is already running and it's too late to start doing odd things out at the system level.

The way you can get around this is with the 'files' key in the Karma configuration. You can add test fixtures here, and Karma will emit them into the page. When you get into binary data, what you have to do is have a build task convert it into something Javascript can tolerate. Typically you'll make a JSON file that contains an escaped string (like Base64) that you can decode back into its raw data.

The https://github.com/karma-runner/karma-ng-html2js-preprocessor HTML2JS preprocessor for Karma does something very similar, and could be a good starting point for you to fork from. It's designed to let you embed HTML files into a test harness for various purposes, and it works by doing the same thing: encoding them into an embeddable format before Karma starts. Using the same mechanism you can embed almost anything you want, if you're willing to bridge the gap with a little pre-processing code.

like image 157
Chad Robinson Avatar answered Sep 05 '25 01:09

Chad Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!