2016-02-29 41 views
0

我想为我的打字稿类从JSON文件中读取数据创建一个测试..如何从因缘访问JSON文件测试

readData<T>(filePath: string): Promise<T> { 
    return Qajax.getJSON(filePath); 
} 

我用的茉莉和因果报应的环境进行测试。我的问题是,即使我添加了因果报应内的任何JSON文件,它不会在Chrome启动

files: [ 
     'libs/angular/angular.js', 
     'libs/angular/angular-route.js', 
     'libs/angular/angular-mocks.js',    
     'libs/collections/collections.js', 
     'tests/framework/common/app_config.json', 
     'tests/package.json', 

     { pattern: 'libs/qajax/qajax.js', included: false }, 
     { pattern: 'libs/q/q.js', included: false }, 

     { pattern: 'tests/framework/**/*.js', included: false }, 
     { pattern: 'tests/toolpattern/**/*.js', included: false }, 
     { pattern: 'tests/test-main.js', included: true }, 

    ] 

加载,你可以在上面因果报应的配置看,我添加了一个名为app_config.json文件。现在我想读取测试文件...

it("read data test.", function (done) { 

    var promise = configurationAccessorImpl.readData("tests/framework/common/app_config.json"); 
    promise.then(result => { 
     console.info("Get configuration test - Success."); 
    }, error => { 
     console.log(error); 
    }); 

}); 

为JSON文件不存在的测试总是失败..

回答

0

目前还不清楚该功能configurationAccessorImpl.readData做什么。但是,如果您尝试使用HTTP请求加载JSON文件,则您可能会遇到问题,因为karma会从/ base相对路径提供测试文件。

试着改变测试:

var promise = configurationAccessorImpl.readData("/base/tests/framework/common/app_config.json"); 

它可能做的工作。

+0

主要的问题在这里是JSON文件没有因果报应环境得到加载。当您从Chrome启动器检查源文件时,您看不到文件“/base/tests/framework/common/app_config.json”..所有其他.js文件都可见。 –

1

库jasmine-jquery为Jasmine JavaScript测试框架提供了几个扩展。 使用扩展API处理测试规范中的HTML,CSS和JSON装置,以读取.json文件。

步骤: - 添加茉莉花的jquery.js到LIBS &茉莉花jquery.d.ts到/库/分型 ,在karma.config添加到库所需的参照,加上JSON固定位置读取文件来自:

// list of files/patterns to load in the browser 
    files: [ 
    ………………………….. 
     'libs/jquery/jquery-1.9.1.js', 
     'libs/jasmine-jquery/jasmine-jquery.js', 
    …………………. 
      // JSON fixture 
     { 
      pattern: 'configuration/*.json', 
      watched: true, 
      served: true, 
      included: false 
     } 
    ], 

- 现在因果报应的测试,可以按如下读取文件:

/// <reference path="../../../libs/typings/jasmine-jquery/jasmine-jquery.d.ts" /> 
    ……………………  
/** 
* @description Unit test for - Getting the configuration file in karma.  
*/ 
it("Configuration file accessor: Read configuration file test.", function (done) { 

    jasmine.getJSONFixtures().fixturesPath = 'base/configuration/'; 

    var jsonData = getJSONFixture('app_config.json'); 
    var appConfig = JSON.stringify(jsonData); 

    // Prints the config file content 
    console.info(appConfig); 
    expect(appConfig).toBeDefined(); 
});