简体   繁体   中英

Cannot read property of undefined in angular karma test

I am testing a service function which makes numerous $http.get() calls. The actual function under test returns a promise. Currently, the test is failing with response is undefined .

Here is the test:

it('should return the list of catalogues', inject(function ($q, bookService) {
    var list;
    var deferred = $q.defer();
    var promise = deferred.promise;

    promise.then(function (response) {
        list = response.success; // Cannot read property 'success' of undefined
    });

    bookService.getCatalogues().then(function (response) {
        deferred.resolve(response); // this line is hit first
    });

    $httpBackend.flush();

    expect(list).toEqual(listOfBooks); // listOfBooks is defined outside test
}));

What am I doing wrong?

Based on this post I have resolved my problem with the following code (please forgive the change in context from book to user):

    describe('user-service', function () {
        var $httpBackend, $q, $rootScope;
        var mockUserData = { "d": { "firstName": "Matt", "lastName": "Lenny" };

        beforeEach(module('users'));

        beforeEach(inject(function (_$httpBackend_,_$q_,_$rootScope_) {
            $httpBackend = _$httpBackend_;
            $q = _$q_;
            $rootScope = _$rootScope_;

            $httpBackend.when('GET', /(.*)\/user\/api/).respond(200, mockUserData);
        }));

        it('should return the user object', inject(function (userService) {
            var user;

            var deferred = $q.defer();
            var promise = deferred.promise;

            promise.then(function (response) {
                user = response;
            });

            userService.getUserInfo().then(function (response) {
                deferred.resolve(response);
            });

            $rootScope.$digest();

            $httpBackend.flush();

            expect(user).toEqual(mockUserData.d);
        }));
    });

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