mardi 26 mai 2015

Unit testing angular event processing

In my Angular code I have a code in a service which returns a promise, something like:

function returnPromise() {
    var deffered = $q.defer();
    service.deferred = deffered;
    return deffered.promise;
}

In another part of the code I wait on this promise to get resolved:

service.returnPromise().then(function(status) {
        // do some work
    }, function() {
        // do something else
    });

The promise is resolved when en event is emitted, so there is code reacting to an event:

$rootScope.$on('success', service._success);

and the service._success resolves the promise:

service._success = function() {
    if (service.paymentDeferred) {
        service.paymentDeferred.resolve();
        delete service.paymentDeferred;
    }
};

I would like to test the code which waits for the promise.

In my test I have something like:

it('success', function(done) {
    // Given

    // When
    $scope.methodWhichWaitsOnPromise();
    service._success(); // resolves the promise

    // Then
    expect($scope.success).to.be.equal(true); // $scope.success is undefined
    done();
});

Expect assertion fails because of asynchronous nature of these calls - the expect is hit before the code which responds to promise resolution is executed.

I test with Mocka and Karma.

How do I test this kind of code?

Aucun commentaire:

Enregistrer un commentaire