Unit Testing: AngularJS + Karma + Jasmine, loading local JSON

I’m writing unit tests for a project the requires some fairly complex json objects. They have become too verbose to plug into the spec file and I’d like to import local json files into my tests. I’ve tried a number of solutions that don’t really work for this project: Loading a mock JSON file within Karma+AngularJS test Angular-Jasmine, loading json How to load external Json file using karma+Jasmine for angularJS testing?/ and using javascript with XMLHttpRequest()…. What’s the proper way to go about loading external files into the spec without creating new dependencies?

Answer

I think the best way for testing in your case is to use $httpBackend. It allows to use your $resource or $http and provide them with test data.

And if you have to deal with large json objects you can define them in separate js files (in functions), include those files in your test js bundle and just call those functions to return your json when you setup $httpBackend service. Hope this helps.

Update Since tests are just plain old js you can create a separate js file. And declare a function in it which will return your json.

(function (window) {
    'use strict';

    if (!window.myJsonMocks){
      window.myJsonMocks = {}; //creating the object that will contain all the functions with json
    }

    window.myJsonMocks.myCustomersQueryResultJson = function(){
      return '{"value":[{"CategoryInfo":{"Id":1,"Type":1},"Caption":"Test","Path":"1/#/1"},{"CategoryInfo":{"Id":2,"Type":1},"Caption":"new","Path":"2/#/2"},{"CategoryInfo":{"Id":3,"Type":2},"Caption":"Another one","Path":"3/#/3"}]}'
    };
})(window);

Since you declare it as IIFE it will register your function in Global scope so that it will be available in your Tests. Just make sure you include it before your test scenarios. And then you just call

$httpBackend.when('GET', 'api/customerssdata').respond(window.myJsonMocks.myCustomersQueryResultJson());

Leave a Reply

Your email address will not be published. Required fields are marked *