10

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.

3 Answers 3

15

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
Sign up to request clarification or add additional context in comments.

4 Comments

Why is this answer downvoted? seems like a valid alternative to me. Some reason why using require is not desired?
@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.
I'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.
@RobertHenderson require('./data.json') works fine for me without your trick, but I see you were writing a couple of years ago.
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}

1 Comment

It looks like this requires jasmine-jquery library.
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);
});

2 Comments

I want to access it from local stystem any(*.json) file using karma/jasmine for angularJS testing
jasmine.getFixtures().fixturesPath = 'base/test/'; staticData= JSON.parse(jasmine.getFixtures().read("staticData.json"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.