Can anyone provide me an example in PLUNKER that how to load JSON file for karma/jasmine test.I want to read the data from JSON file for the test cases i am writing.I have been searching but nowhere they mentioned clear example on how to do it? I appreciate it if anyone can provide with the example.
Asked
Active
Viewed 1.1k times
3 Answers
14
You can load an external json data file using require
var data = require('./data.json');
console.log(data);
// Your test cases goes here and you can use data object

egor.zhdan
- 4,555
- 6
- 39
- 53

Pradeep Lakku
- 241
- 2
- 7
-
1Why is this answer downvoted? seems like a valid alternative to me. Some reason why using `require` is not desired? – Daniel Dec 04 '17 at 22:09
-
1@MondKin, I use require in my test files all the time to pull in necessary libraries and resources. I don't know why this was downvoted. I just upvoted. – Robert Henderson Jan 17 '18 at 23:10
-
3I'd like to add that you need to use a trick when using require if you are trying to require a file that does not have the .js extension. The example above won't necessarily work as '.js' will be appended to the end and not be able to find `data.json.js`. The workaround is to add a fake URL parameter like `require('./data.json?test=')`. This will turn into `data.json?test=.js` which will still locate the file. – Robert Henderson Jan 17 '18 at 23:38
-
@RobertHenderson require('./data.json') works fine for me without your trick, but I see you were writing a couple of years ago. – Paul Lynch Nov 14 '18 at 16:44
7
Set the path to find your file, in this case my file (staticData.json) is located under /test folder.
jasmine.getFixtures().fixturesPath = 'base/test/';
staticData= JSON.parse(jasmine.getFixtures().read("staticData.json"));
You have to add also the pattern in the karma.conf.js file, something like:
{ pattern: 'test/**/*.json', included: false, served: true}

Daniela
- 318
- 3
- 12
1
Do you want to read the JSON file from a webserver or a local file system? No one can give an example of loading from a local file system from Plunker, since it runs in a web browser and is denied access to the file system.
Here is an example of how to load a JSON file from disk in any Node.js program, this should work for Karma/Jasmine:
var fs = require('fs');
var filename = './test.json';
fs.readFile(filename, 'utf8', function (err, data) {
if (err) {
console.log('Error: ' + err);
return;
}
data = JSON.parse(data);
console.dir(data);
});

JBCP
- 13,109
- 9
- 73
- 111
-
I want to access it from local stystem any(*.json) file using karma/jasmine for angularJS testing – user2573410 Feb 25 '14 at 05:32
-
jasmine.getFixtures().fixturesPath = 'base/test/'; staticData= JSON.parse(jasmine.getFixtures().read("staticData.json")); – Daniela Jan 18 '16 at 04:20