background preloader

Promises

Facebook Twitter

Prevent AngularJS to return promise with cached data. Angularjs promise not being resolved in unit test. AngularJs unit test - mocked promise not executing "then" How do I mock the result in a $http.get promise when testing my AngularJS controller. Mocking Promises in Unit Tests | Coding Smackdown TV. 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. A Simple Service that uses $http To demonstrate how to test a controller that contains the above code pattern, we first need to create a simple service which uses the $http service and returns the promise from the $http() method.

We will next create a simple app and controller that will use the service. AngularJs unit test - mocked promise not executing "then" Angularjs promise not being resolved in unit test.