在Karma AngularJS测试中加载模拟JSON文件
我有一个AngularJS应用程序设置与测试使用Karma Jasmine。我有一个功能,我想测试,需要一个大的JSON对象,将其转换为一种更易于消费的格式,由应用程序的其余部分,并返回转换的对象。而已。
对于我的测试,我想你有单独的JSON文件(* .json)只有模拟JSON内容 – 没有脚本。对于测试,我想能够加载JSON文件,并将对象泵入我测试的函数。 我知道我可以嵌入JSON在一个模拟工厂,如下所述:http://dailyjs.com/2013/05/16/angularjs-5/,但我真的希望JSON不包含在脚本中 – 只是直接的JSON文件。 我试过几件事,但我在这方面相当noob。首先,我设置我的Karma包含我的JSON文件只是为了看它会做什么: files = [ ... 'mock-data/**/*.json' ... ] 这导致: Chrome 27.0 (Mac) ERROR Uncaught SyntaxError: Unexpected token : at /Users/aaron/p4workspace4/depot/sitecatalyst/branches/anomaly_detection/client/anomaly-detection/mock-data/two-metrics-with-anomalies.json:2 所以我改变它只是服务文件,而不是“包括”他们: files = [ ... { pattern: 'mock-data/**/*.json',included: false } ... ] 现在,他们只提供服务,我想我会尝试加载在文件中使用$ http从我的规格内: $http('mock-data/two-metrics-with-anomalies.json') 当我运行规格我收到: Error: Unexpected request: GET mock-data/two-metrics-with-anomalies.json 在我的理解意味着它期望一个嘲笑响应从$ httpBackend。所以…在这一点上,我不知道如何加载文件使用Angular实用程序,所以我想我会尝试jQuery,看看我是否至少可以让它工作: $.getJSON('mock-data/two-metrics-with-anomalies.json').done(function(data) { console.log(data); }).fail(function(response) { console.log(response); }); 这导致: Chrome 27.0 (Mac) LOG: { readyState: 4,responseText: 'NOT FOUND',status: 404,statusText: 'Not Found' } 我在查尔斯检查这个请求,并提出请求 /mock-data/two-metrics-with-anomalies.json 而我已配置为由Karma“包括”的其余文件正在请求,例如: /base/src/app.js 显然Karma设置某种基本目录来提供文件。所以对于踢我改变了我的jquery数据请求 $.getJSON('base/mock-data/two-metrics-with-anomalies.json')... 它的工作原理!但现在我觉得肮脏,需要洗个澡。帮助我再次感觉清洁。
我使用角度设置与角种子。我最终用直接的.json夹具文件和jasmine-jquery.js解决这个问题。其他人已经暗示了这个答案,但我花了一段时间把所有的东西在正确的地方。我希望这可以帮助别人。
我有我的json文件在一个文件夹/ test / mock和我的webapp是在/应用程序。 我的karma.conf.js有这些条目(其他): basePath: '../',files: [ ... 'test/vendor/jasmine-jquery.js','test/unit/**/*.js',// fixtures {pattern: 'test/mock/*.json',watched: true,served: true,included: false} ], 那么我的测试文件有: describe('JobsCtrl',function(){ var $httpBackend,createController,scope; beforeEach(inject(function ($injector,$rootScope,$controller) { $httpBackend = $injector.get('$httpBackend'); jasmine.getJSONFixtures().fixturesPath='base/test/mock'; $httpBackend.whenGET('http://blahblahurl/resultset/').respond( getJSONFixture('test_resultset_list.json') ); scope = $rootScope.$new(); $controller('JobsCtrl',{'$scope': scope}); })); it('should have some resultsets',function() { $httpBackend.flush(); expect(scope.result_sets.length).toBe(59); }); }); 真正的窍门是jasmine.getJSONFixtures()。fixturesPath =’base / test / mock’; Error: JSONFixture could not be loaded: /test/mock/test_resultset_list.json (status: error,message: undefined) at /Users/camd/gitspace/treeherder-ui/webapp/test/vendor/jasmine-jquery.js:295 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |