AngularJS, code.explode, Coding

Mocking Promises in Unit Tests

If you’ve spent some time writing services in AngularJS that front-end Web APIs, you have probably used the $http service. One of the prevalent code patterns that tends to develop involves calling the .then() method on the promise that is returned from the various $http methods. This in effect waits to execute code until the asynchronous request returns and the promise is resolved.

The more complicated the Web API you are interacting with, the more your controller code tends to end up with several bits of code as shown below:

    user.requestCurrentUser().then(function() {
        $scope.currentUser = user.getCurrentUser();
    });

Testing this code can be a bit problemsome for newcomers to AngularJS. This article shows a simple way to mock your services to provide similar functionality so you can unit test your controllers that contain these type of code patterns.

Continue reading

Standard