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

前端 未结 3 964
终归单人心
终归单人心 2020-12-17 22:38

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 b

相关标签:
3条回答
  • 2020-12-17 23:20

    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
    0 讨论(0)
  • 2020-12-17 23:29

    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);
    });
    
    0 讨论(0)
  • 2020-12-17 23:43

    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}
    
    0 讨论(0)
提交回复
热议问题