0

I have a very simple function in a jasmine test where I am simply returning $q.reject

var mockFunction = function() {
                return $q.reject("error");
        };

which I call:

mockFunction().catch(function(){
// ... blah
});

the catch callback function is never being invoked. If I understand correctly $q.resolve should create a promise, rejected immediately and return the rejected promise so I'm not sure why this is not working

Any insights are appreciated. Thanks!

Jonny
  • 2,787
  • 10
  • 40
  • 62
  • 1
    Are you writing tests? Promise resolution/rejection is tied to the angular digest loop, so frequently in tests you need to add a `$rootScope.$apply()` call. – mgilson Mar 11 '16 at 16:45
  • you're right, stupid me. Thanks – Jonny Mar 11 '16 at 16:49

1 Answers1

2

$q promise chains aren't executed automatically in specs, it should be

mockFunction().catch(function(){
// ... blah
});
$rootScope.$digest();

to launch it, the chain will be executed synchronously in this case.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • I'm not sure that it makes any real difference, but FWIW the [docs](https://docs.angularjs.org/api/ng/service/$q#testing) use `$rootScope.$apply()` instead of `$digest` – mgilson Mar 11 '16 at 16:50
  • It is the matter of semantics if it is $digest or $apply. In production the one may always want to use $apply, preferably with expression argument, it essentially puts safeguards around $digest. $rootScope.$digest() is widely used in specs to just trigger a digest on root scope, there's no danger to use it explicitly there. – Estus Flask Mar 11 '16 at 17:01