0

I have a test I want to do before I make an ajax call. If that test is a failure condition I want to immediately reject, but it seems I cannot do that:

  svc.test = function(foo){
    var def = $q.defer();

    if (!foo){
      def.reject(new Error('failed'));
    } else {
      // get data via ajax here
      def.resolve({})
    }

    return def.promise;
  };

I tried adding setTimeout around the def.reject() but then my unit test doesn't work.

  it.only('should error ', function(){
    return expect(MyServices.test()).to.eventually.be.rejectedWith('failed');
  });

Using native promise works fine, but I need to do this with $q:

  return Promise.reject(new Error('failed'));
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
chovy
  • 72,281
  • 52
  • 227
  • 295
  • I have no idea what `to.eventually.be.rejectedWith` does, but your promise is not rejected with 'failed'. It's rejected with new Error('failed'). Moreover, if you never call $scope.$apply(), the promise will stay pending. – JB Nizet Apr 15 '16 at 22:13
  • its from `chai-as-promised` -- the `rejectedWith` expects an error object. – chovy Apr 15 '16 at 22:16
  • Then you most probably need to call $scope.$apply() (or $rootScope.$apply()). – JB Nizet Apr 15 '16 at 22:18
  • its a service, there is no scope. – chovy Apr 15 '16 at 22:21
  • $rootScope is a service, too. Inject it in your test, and call $rootScope.$apply(). – JB Nizet Apr 15 '16 at 22:22
  • this makes no sense. i'm returning immediately. and $rootScope should not be in services, as I understand it. – chovy Apr 15 '16 at 22:23
  • @chovy - this [issue](https://github.com/angular/angular.js/issues/9954) deals with your problem, and offer solutions. The problem is tied to `$apply` as JB Nizet wrote. – Ori Drori Apr 15 '16 at 22:25
  • First, it's perfectly fine to use $rootScope from a service. Second, I'm not telling you to call $apply() from your service, but from your test. Third, yes, it makes perfect sense, since angular promises are actually resolved/rejected at the next digest loop. It's documented, you know: https://docs.angularjs.org/api/ng/service/$q#testing. – JB Nizet Apr 15 '16 at 22:26
  • Ok, I got it to resolve, but `chai-as-promised` is just timing out now: `var resolvedValue = MyServices.test(); $rootScope.$apply(); return resolvedValue.should.eventually.be.rejectedWith(TypeError, 'failed');` – chovy Apr 15 '16 at 22:44
  • Possible duplicate of [Return a Promise that promises to throw error](http://stackoverflow.com/questions/33292312/return-a-promise-that-promises-to-throw-error) – Bergi Jun 09 '16 at 13:38

0 Answers0