mercredi 6 mai 2015

async testing angular controller and services with jasmine

I am just getting started with Angular. I really like the design and it's actually very nice to test. One thing I can't get to seem working is testing asynchronous services and their hookups to controllers.
Just to make sure I did understand Angulars $q correctly, if my service looks something like this;

 this.AsyncTask = function (params) {
        var deferred = $q.defer();
        doAsyncStuff(params, function () {
            if (iAmReady) {
                deferred.resolve("Success");
            }
        });
        return deferred.promise;
    };  

This essentially does the following as I see it. Do async stuff and return a promise (that it is working on the async stuff). When the event is processed at some point, "notify" the promise that the async task is done and return back some values to it. Now in my controller I would do.

MyService.AsyncTask(params).then(function (value) {
    if (value) {
        $scope.success = value;
    }
});

Here the controller instructs the service to do the AsyncTask (with some params) and the .then tells when the service is done with the async task, and the controller can do some logic based on that result.
So far so good, this actually in production does exactly what I want, however I am not able to unit test it with jasmine.
I tried a lot of possible solutions out there (including Angulars official example on that as well as jasmines done functionality) but I cant seem to make it work and these are the problems I'm facing:

  1. In my service, either the expect never gets called (or be more precisely gets called too early since the results are correct when debugging)
  2. Or when I use jasmines done (for example inside a .then) in my mocked up controller, it always times out and never gets called.
  3. When using the way described in Angular's unit test example, calling $rootScope.$apply doesn't do anything for me and problem 1 again.

So I would be really glad if you could give me some hints on how to generally approach this.

Aucun commentaire:

Enregistrer un commentaire