2016-02-29 21 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(); 
});