Angular Unit Tests for Promise Chains that use .then()

A quick and simple way to test promises and then methods is to use $q.resolve()

I tried very complicated approaches including using $httpBackend, but in the end there was this very lightweight and simple solution to test promises in angular.

Use spyOn.and.returnValue and return $q.resolve() with scope.$digest()

Syntax:

1
2
3
spyOn(object, ‘method’).and.returnValue($q.resolve(data));

scope.$digest();

Data can be anything, a primitive value or an object for example.

Remember to use scope.$digest() to trigger it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.