简体   繁体   中英

How to test a service in Angular with $q

I have a simple service:

.factory('list', function($q, $timeout) {
    return {
        get: function() {
            var dfd = $q.defer();

            $timeout(function () {
                dfd.resolve(['label1', 'label2']);
            }, 10);

            return dfd.promise;
        }
    };
});

and want to test it. So I created:

describe('list', function() {

    var list, labels;

    beforeEach(module('app'));
    beforeEach(inject(function($q, _list_) {
       list = _list_;

       spyOn(list, 'get').and.callThrough();

       list.get().then(function(result) {
           labels = result;
       });
    }));

    describe('getting list of labels', function() {

        it('should return list of labels', function() {
            expect(labels).not.toBe(undefined);
            expect(Array.isArray(labels)).toBeTruthy();
        });

     });

});

But the problem is, that the callback in then function isn't executed, even though the get method in service returns promise. Am I doing something wrong? I read about callFake method in Jasmine, but to be honest I don't see a point in using it. Could you explain what are some benefits of using it? Btw I have Jasmine 2.0 and latest angular with angular-mocks.

The answer was simple and I forgot about it. Due to the fact I used $timeout I should have called flush afterwards.

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