Read File inside a Jasmine Karma test

一笑奈何 提交于 2021-02-19 05:18:28

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/24763225/read-file-inside-a-jasmine-karma-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!