简体   繁体   中英

Test Angular Service that Returns a $q Promise in Jasmine 2.0 Asynchronously

I have a spec which tests the result of a promise.

The promise resolves, but the then , catch , and finally handlers never seem to fire, and call done();

As a result, the spec times out and fails (see screen shot of Chrome Developer Console).

Jasmine suite and spec

describe("promise suite", function () {
        var someMethod = function() {
            var deferred = $q.defer();
            setTimeout(function() {
                console.log('All done calling resolve');
                deferred.resolve('all done');
            }, 500);
            return deferred.promise;
        }
        iit("promise spec", function (done) {
            someMethod()
                .then(function(message) {
                    console.log('promise method resolved, running expectation');
                    expect(message).toBe('all done');
                    done();
                })
                .catch(function(error) {
                    console.log('promise was rejected ', error);
                    done();
                })
                .finally(function() {
                    console.log('calling done from finally');
                    done();
                });
        });
    });

在此输入图像描述

$ q promises在下一个摘要中得到解决...所以你需要触发一个摘要:

$rootScope.$digest();

Tried your code in plunkr and it's working, see the console output.

Since there's no app to bootstrap in the example I'm using https://docs.angularjs.org/api/ng/function/angular.injector with the ng module to get the $q service

http://plnkr.co/edit/pIZ8LVtlyERXVxQB9HI2?p=preview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM