Nate
Nate

Reputation: 1750

AngularJS better way to read config file?

I built a angularJS app that I wanted dynamically configured, so I created a config.json file with the needed configurations, and decided to load the config file in app.config as such:

angular.module("myapp",[]).config([ my injections] , function(my providers){
if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.open("GET","config.json"); //my config file
    xhr.send();
    xhr.onreadystatechange=function()
    {
        if (xhr.readyState==4 && xhr.status==200)
        {
            //config file parsed, set up params
        }
    }
})

The reason I am doing it this way is because $http is not injected in config state, and I do not want to "configure" the app at a controller level.

The application works fine. it does what I want to do, and everything works great...EXCEPT when it comes to unit testing (with karma + jasmine).

even though in karma.conf i have:

{pattern: 'config.json',served:true,watched:false,included:false}

defined, when I launch karma, I get a cli [WARN] about config.json 404. and my unit tests to see if everything is configured, fails (i.e it didnt read config.json)

Is there a better way to write config files for unit testing?

Upvotes: 3

Views: 1097

Answers (1)

In our apps we have external file config.js, which contains just ordinary module which provides constants with configuration.

angular.module('myAppPrefixconfig')
   .constant('PLAIN_CONSTANT', 'value'),
   .constant('APP_CONFIG', {...});

In your app you have dependancy on it, and there is ordinary http request - which can be resolved by your backend with proper configuration.

In Karma tests you can then provide 'testing config' directly in karma.conf.

Upvotes: 1

Related Questions