Reputation: 81
I am trying to create a test for my typescript class which reads data from a json file..
readData<T>(filePath: string): Promise<T> {
return Qajax.getJSON(filePath);
}
I am using Jasmine and karma environment for testing. My issue is that even if I add any json files inside the karma, it won't be loaded in chrome launcher
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 },
]
As you can see in the above karma config, I have added a file called app_config.json. Now I am trying to read that file from test...
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);
});
});
The test always fails as the json file does not exists..
Upvotes: 2
Views: 3819
Reputation: 11
Library jasmine-jquery provides couple of extensions for the Jasmine JavaScript Testing Framework. Used the extension API for handling HTML, CSS, and JSON fixtures in test specs, to read the .json file.
Steps: - add jasmine-jquery.js to libs & jasmine-jquery.d.ts to / libs/typings , add required references in karma.config to the libs, add JSON fixture location to read the files from:
// 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
}
],
- now in karma test, can read the file as follows:
/// <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();
});
Upvotes: 1
Reputation: 6059
It's not clear what the function configurationAccessorImpl.readData does. But if you're trying to load the JSON file using an HTTP request, you might be having a problem with the fact that karma serves test files from a /base relative path.
Try and change your test to:
var promise = configurationAccessorImpl.readData("/base/tests/framework/common/app_config.json");
It might do the job.
Upvotes: 0