在 Karma+AngularJS 测试中加载模拟 JSON 文件 [英] Loading a mock JSON file within Karma+AngularJS test

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

问题描述

我有一个使用 Karma+Jasmine 进行测试的 AngularJS 应用程序.我有一个要测试的函数,它接受一个大型 JSON 对象,将其转换为应用程序其余部分更易于使用的格式,然后返回转换后的对象.就是这样.

I have an AngularJS app set up with tests using Karma+Jasmine. I have a function I want to test that takes a large JSON object, converts it to a format that's more consumable by the rest of the app, and returns that converted object. That's it.

对于我的测试,我希望您拥有单独的 JSON 文件 (*.json),其中仅包含模拟 JSON 内容——没有脚本.对于测试,我希望能够加载 JSON 文件并将对象泵入我正在测试的函数中.

For my tests, I'd like you have separate JSON files (*.json) with mock JSON content only--no script. For the test, I'd like to be able to load the JSON file in and pump the object into the function I'm testing.

我知道我可以将 JSON 嵌入到模拟工厂中,如下所述:http://dailyjs.com/2013/05/16/angularjs-5/ 但我真的希望 JSON 不包含在脚本中——只是直接的 JSON 文件.

I know I can embed the JSON within a mock factory as described here: http://dailyjs.com/2013/05/16/angularjs-5/ but I really want the JSON to not be contained within script--just straight JSON files.

我尝试了一些东西,但我在这方面相当菜鸟.首先,我将 Karma 设置为包含我的 JSON 文件,只是为了看看它会做什么:

I've tried a few things but I'm fairly noob in this area. First, I set up my Karma to include my JSON file just to see what it would do:

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

然后我将其更改为仅提供文件而不是包含"它们:

So then I changed it to just serve the files and not "include" them:

files = [
    ...
    { pattern: 'mock-data/**/*.json', included: false }
    ...
]

既然它们只提供服务,我想我会尝试在我的规范中使用 $http 加载文件:

Now that they're only served, I thought I'd try to load in the file using $http from within my spec:

$http('mock-data/two-metrics-with-anomalies.json')

当我运行我收到的规范时:

When I ran the spec I received:

Error: Unexpected request: GET mock-data/two-metrics-with-anomalies.json

根据我的理解,这意味着它期望来自 $httpBackend 的模拟响应.所以......此时我不知道如何使用 Angular 实用程序加载文件,所以我想我会尝试使用 jQuery 看看我是否至少可以让它工作:

Which in my understanding means it expects a mocked response from $httpBackend. So...at this point I didn't know how to load the file using Angular utilities so I thought I'd try jQuery to see if I could at least get that to work:

$.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' }

我在 Charles 中检查了这个请求,它正在向

I inspect this request in Charles and it's making a request to

/mock-data/two-metrics-with-anomalies.json

而我配置为由 Karma包含"的其余文件正在请求,例如:

Whereas the rest of the files I've configured to be "included" by Karma are being requested at, for example:

/base/src/app.js

显然 Karma 正在设置某种基本目录来提供文件.所以为了踢球,我将我的 jquery 数据请求更改为

Apparently Karma's setting up some sort of base directory to serve the files from. So for kicks I changed my jquery data request to

$.getJSON('base/mock-data/two-metrics-with-anomalies.json')...

它有效!但现在我觉得很脏,需要洗个澡.帮我重新感觉干净.

And it works! But now I feel dirty and need to take a shower. Help me feel clean again.

推荐答案

我正在使用带有 angular 种子的 angular 设置.我最终用直接的 .json 固定文件和 jasmine-jquery.js 解决了这个问题.其他人提到了这个答案,但我花了一段时间才把所有的部分都放在正确的地方.我希望这对其他人有帮助.

I'm using an angular setup with angular seed. I ended up solving this with straight .json fixture files and jasmine-jquery.js. Others had alluded to this answer, but it took me a while to get all the pieces in the right place. I hope this helps someone else.

我的 json 文件位于 /test/mock 文件夹中,而我的 web 应用程序位于 /app 中.

I have my json files in a folder /test/mock and my webapp is in /app.

我的 karma.conf.js 有这些条目(以及其他):

my karma.conf.js has these entries (among others):

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';我最初将它设置为 test/mock 但它需要 base 在那里.没有基础,我得到了这样的错误:

The real trick was the jasmine.getJSONFixtures().fixturesPath='base/test/mock'; I had originally set it to just test/mock but it needed the base in there. Without the base, I got errors like this:

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

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

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