Question

Just discovered Qunit and I'm writing some tests for the firs time. Now this might be a weird question, but here goes. If I have a function that reads json data from a file, how do I test it? I could mock the actual getJSON as suggested here. but wouldn't that defeat the purpose of the test? I mean the file could be missing, empty, filled with non valid JSON,... So if I mock the getJSON I can't test that. Or am I looking at it wrong and should this function not be tested at all since I'm providing the file?

function GetJSONFromFile(){
  var fileData;
  $.getJSON( "js/file.json", function(data) {   
    fileData = data;        
  })
  .fail(function(jqxhr, textStatus, error) {
    var err = textStatus + ", " + error;
    console.log(err);
  });   
  return fileData;
}
Was it helpful?

Solution

This can be done with mockJax: https://github.com/appendto/jquery-mockjax/ Here you can intercept the request and sent it to a test json file. It also allow you to return other data types, so you can test the "non valid json" issue.

$.mockjax({
  url: '/restful/api',
  proxy: '/mocks/data.json'
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top