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

标签 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...

它通过了。

最佳答案

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

您可以通过夹具提供 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 }
    ],

关于javascript - 从 Karma/Jasmine 测试加载外部文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20938320/

相关文章:

javascript - Node 调度仅运行一次

PHP Composer 无法为我的项目解析 composer.json 文件

jquery - 使用 JSON 调用 asmx Web 服务器时出现内部服务器错误

java - 如何设置 IntelliJ IDEA 环境以进行 JDK8 开发?

maven - 使用 IntelliJ 12.1.2 和 Maven 项目时 Grails 应用程序不同步

scala 项目在 intellij 中不起作用

javascript - 滑入滑出div

javascript - 排除移动设备中的 javascript 窗口调整大小

javascript - 如何将外部 util 类包含并内联到主 TypeScript 应用程序中?

java - 我已经使用了 api,但对如何使用改造获取基本 url 和参数感到困惑