How to load external Json file using karma+Jasmine for angularJS testing?/

故事扮演 提交于 2019-12-18 04:52:47

问题


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.


回答1:


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



回答2:


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}



回答3:


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);
});


来源:https://stackoverflow.com/questions/22003472/how-to-load-external-json-file-using-karmajasmine-for-angularjs-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!