在Jasmine Karma测试中读取文件 [英] Read File inside a Jasmine Karma test

查看:69
本文介绍了在Jasmine Karma测试中读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项服务可对上传的文件进行处理.我在服务中有一个函数,该函数基本上将上载的(.xlxs)文件转换为工作簿.我想为此特定功能编写测试用例. (不上传到服务器,而是上传到浏览器) 任何人都可以建议如何从单元测试方案内部访问测试文件(例如test_something.xlxs).我想将文件读取为二进制字符串,然后将该对象传递给服务方法.

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.

我使用的单元测试框架是Karma + Jasmine.

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

推荐答案

这是很痛苦的,因为当您驾驭安全带时,您正处在沙盒浏览器领域,并且无法真正轻松地访问外部文件. Karma的工作原理基本上是创建一个伪造的HTML页面包装程序,然后通过PhantomJS,Jasmine等将其加载到浏览器中进行测试.当测试工具开始运行时,该浏览器已经在运行,现在开始进行一些奇怪的事情为时已晚.在系统级别.

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.

解决此问题的方法是使用Karma配置中的文件"键.您可以在此处添加测试治具,Karma会将其发射到页面中.当您进入二进制数据时,您需要做的是一个构建任务,将其转换为Javascript可以容忍的东西.通常,您将制作一个包含转义字符串(如Base64)的JSON文件,您可以将其解码回原始数据.

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.

https://github.com/karma-runner/karma-ng -用于Karma的-html2js-preprocessor HTML2JS预处理器具有非常相似的功能,对于您而言,这可能是一个很好的起点.它旨在让您出于各种目的将HTML文件嵌入到测试工具中,并且通过执行相同的操作来工作:在Karma启动之前将它们编码为可嵌入的格式.如果您愿意用少量的预处理代码来弥合差距,则可以使用相同的机制嵌入几乎任何所需的内容.

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.

这篇关于在Jasmine Karma测试中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆