从Karma / Jasmine测试加载外部文件

时间:2014-01-05 19:49:21

标签: javascript json intellij-idea jasmine karma-runner

我正在尝试完成Jasmine测试(使用Karma和IntelliJ 13)来验证JSON文件。理想情况下,我的测试只是将JSON文件加载到数据对象中,然后让我解析以检查有效的格式和数据。我不需要在之前或之后验证函数,也不需要针对服务器进行测试。

我的基本设置是这样的:

it("should load an external file", function(){
var asyncCallComplete, result,
            _this = this;
        // asyncCallComplete is set to true when the ajax call is complete
        asyncCallComplete = false;

        // result stores the result of the successful ajax call
        result = null;

        // SECTION 1 - call asynchronous function
        runs(function() {
            return $.ajax('/test/config.json', {
                type: 'GET',
                success: function(data) {
                    asyncCallComplete = true;
                    result = data;
                },
                error: function() {
                    asyncCallComplete = true;
                }
            });
        });

        // SECTION 2 - wait for the asynchronous call to complete
        waitsFor(function() {
            return asyncCallComplete !== false;
        }, "async to complete");

        // SECTION 3 - perform tests
        return runs(function() {
            return expect(result).not.toBeNull();
        });
}

问题在于无论我使用什么路径,都会收到404错误,文件无法加载。我尝试使用此测试服务从远程服务器加载外部JSON结果:

http://date.jsontest.com/

这很有效。

我的测试文件名为/test/mySpec.js,我的karma.conf.js文件位于根目录下。我已经将JSON文件移动到所有这些位置而没有运气。我做错了什么?

更新答案:

根据下面的答案,我将此添加到我的karma.conf.js:

// fixtures
{ pattern: 'test/*.json',
    watched: true,
    served:  true,
    included: false
}

然后,我用这样写了我的测试:

    var json:any;
    it("should load a fixture", function () {
        jasmine.getFixtures().fixturesPath = "base/test/"
        var f = readFixtures("registration.json");
        json = JSON.parse(f);
        expect(json).toBeDefined();

    })

    it("should have a title", function () {
        expect(json.title).toNotBe(null);
    })
    etc...

它过去了。

4 个答案:

答案 0 :(得分:20)

您是否通过karma.config.js提供JSON文件?

您可以通过fixture提供JSON文件:

files: [
      // angular 
      'angular.min.js',
      'angular-route.js',
      'angular-mocks.js',

      // jasmine jquery helper
     'jquery-1.10.2.min.js',
     'jasmine-jquery.js',

      //  app
      '../../public/js/app.js',

      // tests
      '*-spec.js',

      // JSON fixture
      { pattern:  '/test/*.json',
        watched:  true,
        served:   true,
        included: false }
    ],

答案 1 :(得分:7)

通过夹具提供JSON是最简单的,但由于我们的设置,我们不能轻易做到这一点,所以我写了另一个辅助函数:

安装

bower install karma-read-json

用法

  1. 将karma-read-json.js放入您的Karma文件中,例如:

    files = [
    ...
    'bower_components/karma-read-json/karma-read-json.js',
    ...
    ]
    
  2. 确保您的JSON由Karma提供,例如:

    files = [
    ...
    {pattern: 'json/**/*.json', included: false},
    ...
    ]
    
  3. 在测试中使用readJSON功能。例如:

    var valid_respond = readJSON('json/foobar.json');
    $httpBackend.whenGET(/.*/).respond(valid_respond);
    

答案 2 :(得分:2)

如果您尝试加载HTML文件并希望避免使用 jasmine-jquery ,则可以利用 karma-ng-html2js-preprocessor 。< / p>

在你的 karma.conf.js

// generate js files from html templates
preprocessors: {
    'resources/*.html': 'ng-html2js'
},

files: [
    ...
    'resources/*.html'
],

plugins: [
    ...
    'karma-ng-html2js-preprocessor'
],

在你的茉莉花规格中:

beforeEach(module('resources/fragment.html'));

var $templateCache;
beforeEach(inject(function (_$templateCache_) {
    $templateCache = _$templateCache_;
}));

describe('some test', function () {
    it('should do something', function () {
        // --> load the fragment.html content from the template cache <--
        var fragment = $templateCache.get('resources/fragment.html');
        expect(fragment).toBe(...);
    });
});

答案 3 :(得分:0)

您是否尝试过简单地要求json文件并将其作为全局变量存储在测试中?

我正在开发一个Angular2项目(使用Angular CLI),并且使用此设置它可以工作:

// On the very beginning of the file let mockConfig = require('./test/config.json');